javascript原型鏈怎么實(shí)現(xiàn)繼承

這篇文章主要介紹了javascript原型鏈怎么實(shí)現(xiàn)繼承的相關(guān)知識,內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇javascript原型鏈怎么實(shí)現(xiàn)繼承文章都會(huì)有所收獲,下面我們一起來看看吧。

創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供盧龍網(wǎng)站建設(shè)、盧龍做網(wǎng)站、盧龍網(wǎng)站設(shè)計(jì)、盧龍網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、盧龍企業(yè)網(wǎng)站模板建站服務(wù),十多年盧龍做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。

繼承的幾種方式:

① 使用構(gòu)造函數(shù)實(shí)現(xiàn)繼承

function Parent(){
  this.name = 'parent';
}
function Child(){
Parent.call(this); //在子類函數(shù)體里面執(zhí)行父類的構(gòu)造函數(shù)
this.type = 'child';//子類自己的屬性
}

Parent.call(this),this即實(shí)例,使用this執(zhí)行Parent方法,那么就用this.name = 'parent'把屬性

掛載在了this(實(shí)例)上面,以此實(shí)現(xiàn)了繼承。

缺點(diǎn):以上只是讓Child得到了Parent上的屬性,Parent的原型鏈上的屬性并未被繼承。

② 使用原型鏈實(shí)現(xiàn)繼承

function Parent(){
  this.name = 'parent';
}
function Child(){
  this.type = 'child';
}
Child.prototype = new Parent();

解釋:Child.prototype === Chlid實(shí)例的__proto__ === Child實(shí)例的原型

所以當(dāng)我們引用new Child().name時(shí),Child上沒有,然后尋找Child的原型child.__proto__Child.prototypenew Parent(),Parent的實(shí)例上就有name屬性,所以Child實(shí)例就在原型鏈上找到了name屬性,以此實(shí)現(xiàn)了繼承。

缺點(diǎn):可以看出,Child的所有實(shí)例,它們的原型都是同一個(gè),即Parent的實(shí)例:

var a = new Child();
var b = new Child();
a.__proto === b.__proto__; //true

所以,當(dāng)使用 a.name = 'a'重新給name賦值時(shí),b.name也變成了'a',反之亦然。

用instanceof和constructor都無法確認(rèn)實(shí)例到底是Child的還是Parent的。

③ 結(jié)合前兩種取長補(bǔ)短

function Parent(){
  this.name = 'parent';
}
function Child(){
  Parent.call(this);
  this.type = 'child';
}
Child.prototype = new Parent();

缺點(diǎn):在Child()里面用Parent.call(this);執(zhí)行了一次Parent(),然后又使用Child.prototype = new Parent()執(zhí)行了一次Parent()。

改進(jìn)1:

function Parent(){
  this.name = 'parent';
}
function Child(){
  Parent.call(this);
  this.type = 'child';
}
Child.prototype = Parent.prototype;

缺點(diǎn):用instanceof和constructor都無法確認(rèn)實(shí)例到底是Child的還是Parent的。

原因: Child.prototype = Parent.prototype直接從Parent.prototype里面拿到constructor,即Parent。

改進(jìn)2:

function Parent(){
  this.name = 'parent';
}
function Child(){
  Parent.call(this);
  this.type = 'child';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

畫圖說明吧:

var a = new Child();

javascript原型鏈怎么實(shí)現(xiàn)繼承

所以這樣寫我們就構(gòu)造出了原型鏈。

關(guān)于“javascript原型鏈怎么實(shí)現(xiàn)繼承”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“javascript原型鏈怎么實(shí)現(xiàn)繼承”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

當(dāng)前名稱:javascript原型鏈怎么實(shí)現(xiàn)繼承
鏈接URL:http://bm7419.com/article42/psdpec.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊全網(wǎng)營銷推廣、網(wǎng)站策劃、網(wǎng)站制作、用戶體驗(yàn)、商城網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營