JS的繼承方式有很多種,最理想的繼承方式是寄生組合式繼承。
組合繼承(構造函數和原型的組合)會調用兩次父類構造函數的代碼,
function Person(name){
this.name=name;
}
Person.prototype.sayName=function(){
console.log(this.name+' '+this.gender+' '+this.age);
}
function Female(name,gender,age){
Person.call(this,name);//第一次調用父類構造函數
this.age=age;
this.gender=gender;
}
Female.prototype=new Person();//第一次調用父類構造函數
Female.prototype.constrcutor=Female;//因重寫原型而失去constructor屬性,所以要對constrcutor重新賦值
因此引入寄生組合式繼承,即通過借用構造函數來繼承屬性,通過原型鏈的方式來繼承方法,而不需要為子類指定原型而調用父類的構造函數,我們需要拿到的僅僅是父類原型的一個副本。因此可以通過傳入子類和父類的構造函數作為參數,首先創建父類原型的一個復本,并為其添加constrcutor,最后賦給子類的原型。這樣避免了調用兩次父類的構造函數,為其創建多余的屬性。
function inheritPrototype(Female,Person){
var protoType=Object.create(Person.prototype);
protoType.constructor=Female;
Female.prototype=protoType;
}
//取代
//Female.prototype=new Person();
//Female.prototype.constrcutor=Female
inheritPrototype(Female,Person);
Female.prototype.sayAge=function(){
console.log(this.name+' '+this.age);
}
var fm=new Female('skila','female',19);
fm.sayName();//skila female 19
fm.sayAge();skila 19