- 原文:幫你徹底搞懂JS中的prototype、__proto__與constructor
-
__proto__
和constructor
屬性是對(duì)象所獨(dú)有的 -
prototype
屬性是函數(shù)所獨(dú)有的 函數(shù)也是一種對(duì)象
圖中藍(lán)色方塊中讳侨,大寫的部分其實(shí)是個(gè)構(gòu)造函數(shù)
_ _ proto _ _
- 指向
原型對(duì)象
/父對(duì)象 - 該屬性在ES標(biāo)準(zhǔn)定義中的名字應(yīng)該是
[[Prototype]]
- 具體實(shí)現(xiàn)是由瀏覽器代理自己實(shí)現(xiàn)
- 作用:當(dāng)訪問一個(gè)對(duì)象的屬性時(shí),如果該對(duì)象內(nèi)部不存在這個(gè)屬性,那么就會(huì)去它的
__proto__
屬性所指向的那個(gè)對(duì)象里找 - 原型鏈盡頭是
Object
Object.__proto__ = null
prototype
- 指向
函數(shù)的原型對(duì)象
- 函數(shù)獨(dú)有的屬性
- 作用:包含可以由特定類型的所有實(shí)例共享的屬性和方法
- 任何函數(shù)在創(chuàng)建的時(shí)候伶丐,其實(shí)會(huì)默認(rèn)同時(shí)創(chuàng)建該函數(shù)的
prototype對(duì)象
- 指向這個(gè)函數(shù)(其實(shí)所有函數(shù)都可以作為構(gòu)造函數(shù))所創(chuàng)建的實(shí)例的原型對(duì)象
f = new Foo();
f.__proto__ === Foo.prototype; // true
f.__proto__ === Foo().prototype
>>> Uncaught TypeError: Cannot read property 'prototype' of undefined這是因?yàn)?Foo 是函數(shù)對(duì)象悼做,F(xiàn)oo() 是在調(diào)用這個(gè)函數(shù)
constructor
- 指向該對(duì)象的
構(gòu)造函數(shù)
- constructor 屬性的終點(diǎn)就是 Function 這個(gè)函數(shù)
- 實(shí)例化得到的對(duì)象其實(shí)自己是不具有 constructor 屬性
手寫 instanceOf
// left 是個(gè)實(shí)例化得到的對(duì)象
// right 是個(gè)構(gòu)造函數(shù)
function myInstanceOf(left, right) {
left = left.__proto__;
right = right.prototype;
while (true) {
if (!left) {
return false;
}
if (left === right) {
return true;
}
left = left.__proto__;
}
}