javascript原型鏈學(xué)習(xí)記錄之繼承實現(xiàn)方式分析
本文實例講述了javascript原型鏈學(xué)習(xí)記錄之繼承實現(xiàn)方式。分享給大家供大家參考,具體如下:
在慕課網(wǎng)學(xué)習(xí)繼承的筆記:
繼承的幾種方式:
① 使用構(gòu)造函數(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即實例,使用this執(zhí)行Parent方法,那么就用this.name = 'parent'
把屬性
掛載在了this(實例)上面,以此實現(xiàn)了繼承。
缺點:以上只是讓Child得到了Parent上的屬性,Parent的原型鏈上的屬性并未被繼承。
② 使用原型鏈實現(xiàn)繼承
function Parent(){ this.name = 'parent'; } function Child(){ this.type = 'child'; } Child.prototype = new Parent();
解釋:Child.prototype === Chlid實例的__proto__ === Child實例的原型
所以當我們引用new Child().name
時,Child上沒有,然后尋找Child的原型child.__proto__
即Child.prototype
即new Parent()
,Parent的實例上就有name屬性,所以Child實例就在原型鏈上找到了name屬性,以此實現(xiàn)了繼承。
缺點:可以看出,Child的所有實例,它們的原型都是同一個,即Parent的實例:
var a = new Child(); var b = new Child(); a.__proto === b.__proto__; //true
所以,當使用 a.name = 'a'重新給name賦值時,b.name也變成了'a',反之亦然。
用instanceof和constructor都無法確認實例到底是Child的還是Parent的。
③ 結(jié)合前兩種取長補短
function Parent(){ this.name = 'parent'; } function Child(){ Parent.call(this); this.type = 'child'; } Child.prototype = new Parent();
缺點:在Child()里面用Parent.call(this);
執(zhí)行了一次Parent(),然后又使用Child.prototype = new Parent()
執(zhí)行了一次Parent()。
改進1:
function Parent(){ this.name = 'parent'; } function Child(){ Parent.call(this); this.type = 'child'; } Child.prototype = Parent.prototype;
缺點:用instanceof和constructor都無法確認實例到底是Child的還是Parent的。
原因: Child.prototype = Parent.prototype
直接從Parent.prototype
里面拿到constructor,即Parent。
改進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();
所以這樣寫我們就構(gòu)造出了原型鏈。
更多關(guān)于JavaScript相關(guān)內(nèi)容還可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運算用法總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
相關(guān)文章
webpack構(gòu)建打包的性能優(yōu)化實戰(zhàn)指南
webpack是前端開發(fā)中比較常用的打包工具之一,另外還有g(shù)ulp,grunt,下面這篇文章主要給大家介紹了關(guān)于webpack構(gòu)建打包的性能優(yōu)化的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-03-03JavaScript中html畫布的使用與頁面存儲技術(shù)詳解
這篇文章主要介紹了JavaScript中html畫布的使用與頁面存儲技術(shù),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08JavaScript forEach()遍歷函數(shù)使用及介紹
這篇文章主要介紹了JavaScript forEach()遍歷函數(shù)使用及介紹,本文講解了使用forEach遍歷數(shù)組的用法以及提前終止循環(huán)的一個方法技巧,需要的朋友可以參考下2015-07-07