title: js對象原型臼膏、原型鏈
date: 2016-11-24 18:54:08
tags: javascript
categories:
- javascript
設(shè)置對象原型
Object.creat
Object.create() 方法創(chuàng)建一個擁有指定原型和若干個指定屬性的對象仿畸。
Object.create(proto, [ propertiesObject ])
- 參數(shù)
- proto
- 一個對象,作為新創(chuàng)建對象的原型呐萌。
- propertiesObject
- 可選馁痴。該參數(shù)對象是一組屬性與值,該對象的屬性名稱將是新創(chuàng)建的對象的屬性名稱肺孤,值是屬性描述符(這些屬性描述符的結(jié)構(gòu)與Object.defineProperties()的第二個參數(shù)一樣)罗晕。注意:該參數(shù)對象不能是 undefined,另外只有該對象中自身擁有的可枚舉的屬性才有效赠堵,也就是說該對象的原型鏈上屬性是無效的小渊。
- proto
- 拋出異常
- 如果 proto 參數(shù)不是 null 或一個對象值,則拋出一個 TypeError 異常茫叭。
//定義原型對象
var landRover = {
name: 'landRover',
start:function(){
console.log('%s start',this.logo)
},
run:function(){
console.log('%s running',this.logo)
},
stop:function(){
console.log('%s stop',this.logo)
}
}
//使用原型構(gòu)造新的對象
var landWind = Object.create(landRover);
landWind.logo = "landWind";
var landCruiser = Object.create(landRover);
landCruiser.logo = "landCruiser";
構(gòu)造函數(shù)
- 構(gòu)造函數(shù)使用prototype設(shè)置原型
- 使用new關(guān)鍵字創(chuàng)建對象
Car的構(gòu)造函數(shù)
function Car(logo){
this.log = logo || 'unknow name';
}
//設(shè)置Car的prototype屬性
Car.prototype = {
start:function(){
console.log('%s start',this.logo)
},
run:function(){
console.log('%s running',this.logo)
},
stop:function(){
console.log('%s stop',this.logo)
}
}
//創(chuàng)建對象
var landWind = new Car('landWind');
var landRover = new Car('landRover');
原型鏈
//Car的構(gòu)造函數(shù)
function Car(logo){
this.log = logo || 'unknow name';
}
//設(shè)置Car的prototype屬性
Car.prototype = {
start:function(){
console.log('%s start',this.logo)
},
run:function(){
console.log('%s running',this.logo)
},
stop:function(){
console.log('%s stop',this.logo)
}
}
// landRover構(gòu)造函數(shù)
function LandRover(serialno){
this.serialNumber = serialno
}
// 設(shè)置LandRover的prototype屬性
LandRover.prototype = new Car('landRover');
landRover1 = new landRover(10001)
landRover1的原型指向Car的實(shí)例酬屉,這個實(shí)例的原型指向Car的prototype,Car.prototype的原型又指向Object.prototype揍愁,這一系列構(gòu)建了一條原型鏈
而構(gòu)造函數(shù)LandRover和Car作為函數(shù)對象梆惯,其對象原型(proto)指向Function.prototype,Function.prototype指向Object.prototype