這篇文章將為大家詳細講解有關javascript原型鏈中如何實現繼承,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
成都創新互聯公司長期為1000多家客戶提供的網站建設服務,團隊從業經驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯網生態環境。為招遠企業提供專業的做網站、成都網站制作,招遠網站改版等技術服務。擁有10余年豐富建站經驗和眾多成功案例,為您定制開發。具體如下:
繼承的幾種方式:
① 使用構造函數實現繼承
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原型鏈中如何實現繼承-創新互聯
分享路徑:http://vcdvsql.cn/article28/cedpcp.html
成都網站建設公司_創新互聯,為您提供企業網站制作、網站設計公司、網站建設、App開發、Google、動態網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯