JS的繼承方式有很多種,最理想的繼承方式是寄生組合式繼承。
組合繼承(構(gòu)造函數(shù)和原型的組合)會(huì)調(diào)用兩次父類構(gòu)造函數(shù)的代碼,
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);//第一次調(diào)用父類構(gòu)造函數(shù)
this.age=age;
this.gender=gender;
}
Female.prototype=new Person();//第一次調(diào)用父類構(gòu)造函數(shù)
Female.prototype.constrcutor=Female;//因重寫(xiě)原型而失去constructor屬性,所以要對(duì)constrcutor重新賦值
因此引入寄生組合式繼承,即通過(guò)借用構(gòu)造函數(shù)來(lái)繼承屬性,通過(guò)原型鏈的方式來(lái)繼承方法,而不需要為子類指定原型而調(diào)用父類的構(gòu)造函數(shù),我們需要拿到的僅僅是父類原型的一個(gè)副本。因此可以通過(guò)傳入子類和父類的構(gòu)造函數(shù)作為參數(shù),首先創(chuàng)建父類原型的一個(gè)復(fù)本,并為其添加constrcutor,最后賦給子類的原型。這樣避免了調(diào)用兩次父類的構(gòu)造函數(shù),為其創(chuàng)建多余的屬性。
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