javascript原形和原形鏈

一、函數(shù)對(duì)象和普通對(duì)象

javascript中,一切皆是對(duì)象,分為函數(shù)對(duì)象和普通對(duì)象。下面舉一個(gè)簡(jiǎn)單的例子。

function f(){
  console.log("我是函數(shù)")
};
var o={data:"我是普通對(duì)象"};//普通對(duì)象
var f1= new f();//函數(shù)對(duì)象
var f2=new function(){};//函數(shù)對(duì)象

其中,o是普通對(duì)象,f1是函數(shù)對(duì)象,即我們通常所說(shuō)本身等于對(duì)象或者調(diào)用函數(shù)的值為函數(shù)對(duì)象,本身等于對(duì)象的為普通對(duì)象。

二、原形對(duì)象

下面我們把目光聚焦刀函數(shù)對(duì)象,所有函數(shù)對(duì)象在創(chuàng)建時(shí)都會(huì)有很多默認(rèn)屬性,其中有一個(gè)prototype屬性,這就是我們所說(shuō)的原形對(duì)象。注意:普通對(duì)象沒(méi)有原形對(duì)象,但是有____proto__ __屬性。函數(shù)對(duì)象也有____proto__ __屬性。
所有東西存在都是有著自己本身的意義,prototype存在的意義就是用于繼承,舉個(gè)例子。

function f(){
  console.log("我是函數(shù)")
};
f.prototype.common="共有屬性";
var f1= new f();
var f2= new f();
console.log(f1.common);//"共有屬性"
console.log(f2.common);//"共有屬性"

函數(shù)f的共有屬性是 common:"共有屬性",所以它所有的"孩子"全部擁有這個(gè)屬性。

思考:

function f(){
  console.log("我是函數(shù)")
};
f.prototype.common=100;
var f1= new f();
var f2= new f();
f2.common-=20;
console.log(f1.common);//?
console.log(f2.common);//?
f.prototype.common-=30;
console.log(f1.common);//?
console.log(f2.common);//?

f2.common-=20;
console.log(f1.common);//100
console.log(f2.common);//80
f.prototype.common-=30;
console.log(f1.common);//70
console.log(f2.common);//80
你答對(duì)了嗎?

三、原形鏈

所有對(duì)象的____proto__ __屬性都指向它父親的prototype屬性。

function f(){
  console.log("我是函數(shù)")
};
f.prototype.common="共有屬性";
var f1= new f();
console.log(f1.__proto__);//f.prototype(object{common:"共有屬性",等一項(xiàng)})
console.log(f1.__proto__===f.prototype);//true;

這就是為什么自己能用父親的屬性,因?yàn)樽约河幸粋€(gè)____proto__ __屬性,自己的屬性自己當(dāng)然能用。

玩一個(gè)有意思的找爸爸的游戲

function f(){
  console.log("我是函數(shù)")
};
var f1= new f();
console.log(f.__proto__);//function()--所有函數(shù)名的爸爸都是function;
console.log(f1.__proto__);//f1.prototype;
console.log(f1.__proto__.__proto__===f.__proto__.__proto__);//true
console.log(f1.__proto__.__proto__);//object
console.log(f1.__proto__.__proto__.__proto__);//null

四、總結(jié)

記得在網(wǎng)上看到一個(gè)大神的解釋很有意思。

原形鏈

爸爸給哥哥買(mǎi)了很多玩具,這些玩具你也可以使用,之后你生了兒子,你給你兒子買(mǎi)了很多玩具,同時(shí),你哥哥的玩具你也可以給你兒子玩。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容