這篇文章主要介紹了javascript原型鏈怎么實現繼承的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇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原型鏈怎么實現繼承”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“javascript原型鏈怎么實現繼承”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。