轉(zhuǎn)自:http://blog.csdn.net/wxw_317/article/details/49617767
在 JavaScript 中寿谴,原型也是一個(gè)對(duì)象剩檀,通過(guò)原型可以實(shí)現(xiàn)對(duì)象的屬性繼承蛆挫,JavaScript 的對(duì)象中都包含了一個(gè) prototype
內(nèi)部屬性前鹅,這個(gè)屬性所對(duì)應(yīng)的就是該對(duì)象的原型与涡。
prototype
作為對(duì)象的內(nèi)部屬性踱讨,是不能被直接訪問(wèn)的魏蔗。所以為了方便查看一個(gè)對(duì)象的原型,F(xiàn)irefox 和 Chrome 中提供了 __proto__
這個(gè)非標(biāo)準(zhǔn)(不是所有瀏覽器都支持)的訪問(wèn)器:
function Person(name, age) {
this.name = name;
this.age = age;
this.getInfo = function(){
console.log(this.name + " is " + this.age + " years old");
};
}
var will = new Person("Will", 28);
// 測(cè)試:
will.name; // "Will"
will.age; // 28
will.getInfo(); // Will is 28 years old
在上面的代碼中痹筛,通過(guò)了 Person 這個(gè) 構(gòu)造函數(shù) 創(chuàng)建了一個(gè) will 對(duì)象沫勿。下面就通過(guò) will 這個(gè)對(duì)象一步步展開(kāi)了解原型挨约。
查看對(duì)象 will 的原型
will.__proto__
// 結(jié)果:
Object {}
constructor:Person(name, age)
__proto__:Object
person {}
對(duì)象就是對(duì)象 will 的原型,通過(guò) Chrome 展開(kāi)可以看到产雹,person {}
作為一個(gè)原型對(duì)象诫惭,也有 __proto__
屬性(對(duì)應(yīng)原型的原型)。
will.constructor
// 結(jié)果
function Person(name, age){
this.name = name;
this.age = age;
this.getInfo = function(){
console.log(this.name + " is " + this.age + " years old");
};
}
在 JavaScript 的原型對(duì)象中蔓挖,還包含一個(gè) constructor
屬性夕土,這個(gè)屬性對(duì)應(yīng)創(chuàng)建所有指向該原型的實(shí)例的構(gòu)造函數(shù)。
在這里瘟判,will 對(duì)象本身并沒(méi)有 constructor
這個(gè)屬性怨绣,但是通過(guò)原型鏈查找,找到了 will 原型(will.__proto__
)的 constructor
屬性拷获,并得到了 Person 函數(shù)篮撑。
查看對(duì)象 will 的原型(will.__proto__)的原型
will.__proto__ === Person.prototype; // true
Person.prototype.constructor === Person; // true
在 JavaScript 中,每個(gè)函數(shù)都有一個(gè) prototype
屬性匆瓜,當(dāng)一個(gè)函數(shù)被用作構(gòu)造函數(shù)來(lái)創(chuàng)建實(shí)例時(shí)赢笨,該函數(shù)的 prototype
屬性值將被作為原型賦值給所有對(duì)象實(shí)例(也就是設(shè)置實(shí)例的 __proto__
屬性)。也就是說(shuō)驮吱,所有實(shí)例的原型引用的是函數(shù)的 prototype 屬性茧妒。
這里我們用 Person 函數(shù)作為構(gòu)造函數(shù)創(chuàng)建了實(shí)例 will,will 的原型(will.__proto__
)指向函數(shù) Person 的 prototype
屬性(Person.prototype
)左冬,所以結(jié)果為 true
桐筏。
注意: prototype
屬性是函數(shù)對(duì)象特有的,如果不是函數(shù)對(duì)象拇砰,將不會(huì)有這樣一個(gè)屬性梅忌。
// 對(duì)象本身是不具有 prototype 屬性的
will.Prototype
// 結(jié)果
undefined
當(dāng)通過(guò) Person.prototype.__proto__
語(yǔ)句獲取 will 對(duì)象原型的原型時(shí)候,將得到 Object {}
對(duì)象除破,后面將會(huì)看到所有對(duì)象的原型都將追溯到 Object {}
對(duì)象铸鹰。
對(duì)于原型對(duì)象 Person.prototype
的 constructor
,根據(jù)前面的介紹皂岔,將對(duì)應(yīng) Person 函數(shù)本身。
通過(guò)上面可以看到展姐,Person.prototype
對(duì)象和 Person
函數(shù)對(duì)象通過(guò) constructor
和 prototype
屬性實(shí)現(xiàn)了相互引用躁垛。