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)。