現(xiàn)有兩個構(gòu)造函數(shù),如下:
function Animal(){
this.special="動物";
}
function Cat(name,color){
this.name=name;
this.color=color;
}
想在我們想要讓Cat構(gòu)造函數(shù)繼承Animal構(gòu)造函數(shù)中的屬性,有如下方法:
1.在子類構(gòu)造函數(shù)中直接通過call/apply的方式直接引入父類構(gòu)造函數(shù),如下:
function Cat(name,color){
Animal.call(this,arguments);
this.name=name;
this.color=color;
}
var cat=new Cat("喵喵","yellow");
console.log(cat.special);
2.使用prototype屬性:
Cat.prototype=new Animal();//Cat的原型指向Animal的實例
Cat.prototype.constructor=Cat;
var cat1=new Cat("miaomiao","yellow");
console.log(cat1.special);
解釋:
第一行:我們把Cat的原型指向了Animal的實例
Cat.prototype=new Animal();
第二行:
Cat.prototype.constructor=Cat;
每一個構(gòu)造函數(shù)的原型上面都有一個constructor的屬性,這個屬性指向它自己的構(gòu)造函數(shù),即我們在不錯任何操作的情況下,查看Cat.prototype.constructor,會給我們輸出Cat構(gòu)造函數(shù),如下圖:

2020-08-08_221855.png
但現(xiàn)在我們使用prototype屬性實現(xiàn)繼承的時候,把Cat.prototype指向了Animal的實例,那么Cat.prototype.constructor的指向就發(fā)生了變化,如下圖:

222.png
有人會疑惑,指向Animal就指向Animal唄!為什么又要重新指向回來呢???
原因如下:檔我們把Cat實例之后,即cat1,每一個實例同樣都有一個constructor屬性,默認(rèn)調(diào)用的是prototype的constructor屬性,即cat1實例的constructor屬性應(yīng)該調(diào)用的是Cat.prototypr.constructor,即:
cat1.constructor==Cat.prototype.constructor //true

333.png
所以第二行我們要把 Cat.prototype.constructor重新指向Cat;
3.直接繼承prototype
第三種方法是對第二種方法的改進(jìn)。由于Animal對象中,不變的屬性都可以直接寫入Animal.prototype。所以,我們也可以讓Cat()跳過 Animal(),直接繼承Animal.prototype。
第三種方法我們把父類構(gòu)造函數(shù)的屬性放在父類的原型上,即:
function Animal(){}
Animal.prototype.special="動物";
function Cat(name,color){
this.name=name;
this.color=color;
}
Cat.prototype=Animal.prototype;
Cat.prototype.constrctor=Cat;
var cat1=new Cat("miaomiao","yellow");
console.log(cat1.special);
與前一種方法相比,這樣做的優(yōu)點是效率比較高(不用執(zhí)行和建立Animal的實例了),比較省內(nèi)存。缺點是 Cat.prototype和Animal.prototype現(xiàn)在指向了同一個對象,那么任何對Cat.prototype的修改,都會反映到Animal.prototype。
5.拷貝繼承:
function Animal(){}
Animal.prototype.special="動物";
function Cat(name,color){
this.name=name;
this.color=color;
}
function extend(parent,child){
var p=parent.prototype;
var c=child.prototype;
for(var i in p){
c[i]=p[i];
}
c.uber=p;
}
extend(Animal,Cat);
var cat1=new Cat("miaomiao","yellow");
console.log(cat1.special);