js最理想的繼承——寄生組合式繼承

來源:互聯網
上載者:User

js最理想的繼承——寄生組合式繼承

1.傳統的組合式繼承的缺點。

 

 

function SuperType(name,colors){   this.name=name;   this.colors=colors;} SuperType.prototype.getSuperProperty=function(){    return this.name;}function SubType(job,name,colors){     SuperType.call(this,name,colors);  //第二次調用基類的建構函式     this.job=job;  }SubType.prototype=new SuperType();    //第一次調用基類的建構函式SubType.prototype.getSubProperty=function(){ return this.job;}var instance=new SubType("doctor","John",["red","green"]);console.log(instance.getSuperProperty());  //john


 

傳統的組合式繼承,為了使子類擁有自己的執行個體屬性,在子類的建構函式裡調用了基類的建構函式,用於覆蓋原型鏈繼承的共用屬性。所以,組合式繼承會兩次調用基類的建構函式:第一次,子類的原型聲明為基類的一個執行個體;第二次,子類的建構函式中調用基類的建構函式。

2.寄生組合式繼承


function SuperType(name,colors){ this.name=name; this.colors=colors; } SuperType.prototype.getSuperProperty=function(){ return this.name; } function SubType(job,name,colors){ SuperType.call(this,name,colors); this.job=job; } function inherit(subType,superType){ var prototype=Object.create(superType.prototype); prototype.constructor=subType; subType.prototype=prototype; } inherit(subType,superType); SubType.prototype.getSubPrototype=function(){ return this.job; } var instance=new SubType("doctor","John",["red","green"]); console.log(instance.getSuperPrototype());


 



寄生組合式繼承利用inherit()函數完成原型鏈的繼承,這樣我們就不需要專門為了原型繼承,調用基類的建構函式。Object.create(prototype,descpritor)是ECMAScript5 中定義的方法,傳回值是產生對象,第一個參數是產生對象的原型,第二個是對象,用於定義屬性或者方法(https://msdn.microsoft.com/zh-cn/library/ff925952)。






 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.