本文實例講述了javascript原型鏈學習記錄之繼承實現方式。分享給大家供大家參考,具體如下:
在慕課網學習繼承的筆記:
繼承的幾種方式:
① 使用構造函數實現繼承
function Parent(){ this.name = 'parent';}function Child(){Parent.call(this); //在子類函數體里面執行父類的構造函數this.type = 'child';//子類自己的屬性}
Parent.call(this)
,this即實例,使用this執行Parent方法,那么就用this.name = 'parent'
把屬性
掛載在了this(實例)上面,以此實現了繼承。
缺點:以上只是讓Child得到了Parent上的屬性,Parent的原型鏈上的屬性并未被繼承。
② 使用原型鏈實現繼承
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屬性,以此實現了繼承。
缺點:可以看出,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的。
③ 結合前兩種取長補短
function Parent(){ this.name = 'parent';}function Child(){ Parent.call(this); this.type = 'child';}Child.prototype = new Parent();
缺點:在Child()里面用Parent.call(this);
執行了一次Parent(),然后又使用Child.prototype = new Parent()
執行了一次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();
所以這樣寫我們就構造出了原型鏈。
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答