//js對(duì)象的繼承
function Animal(){
this.species = "animal";
}
function Cat(name,color){
this.name = name;
this.color = color;
}
//1.構(gòu)造函數(shù)綁定——使用call或apply方法式曲,將父對(duì)象的構(gòu)造函數(shù)綁定在子對(duì)象上
function Cat(name,color){
Animal.apply(this,arguments);
this.name = name;
this.color = color;
}
var cat1 = new Cat("xiao","red");
console.log("species:"+cat1.species+" name:"+cat1.name+" color:"+cat1.color);
//2.prototype模式——"貓"的prototype對(duì)象忽冻,指向一個(gè)Animal的實(shí)例哼转,那么所有"貓"的實(shí)例肉迫,就能繼承Animal了
Cat.prototype = new Animal();//將prototype變成animal的實(shí)例
var cat1 = new Cat("xiao","red");
/*
任何一個(gè)prototype對(duì)象都有一個(gè)constructor屬性,指向它的構(gòu)造函數(shù)(Cat)
Cat.prototype原來(lái)指向的是Cat,因?yàn)樯厦鎸⑺鎿Q成了Animal的實(shí)例了
所以它的屬性(constructor)也變成了Animal
*/
console.log(Cat.prototype.constructor == Animal);//true
/*
每個(gè)實(shí)例也有一個(gè)constructor屬性尿招,默認(rèn)調(diào)用prototype對(duì)象的constructor屬性失暴。
*/
console.log(cat1.constructor == Cat.prototype.constructor);//true
console.log(cat1.constructor == Animal);//true
//cat1明明是用構(gòu)造函數(shù)Cat生成的,但是現(xiàn)在變成了Animal邀层,所以需要再把它變回原來(lái)的Cat
Cat.prototype.constructor = Cat;
cat1 = new Cat("xiao","red");
console.log(cat1.species); // animal
//結(jié)論异赫,替換一個(gè)構(gòu)造函數(shù)的prototype,一定要將prototype的constructor換回它本身椅挣。
//3.利用空對(duì)象直接繼承prototype
function extend(parent,child){
function f(){};
f.prototype = parent.prototype;
child.prototype = new f();
child.prototype.constructor = child;
child.uber = parent.prototype;//純粹為了備用头岔,可以調(diào)父類(lèi)的原型 uber意思是上一層
}
extend(Animal,Cat);
var cat2 = new Cat("dada","white");
console.log("species:"+cat2.species+" name:"+cat2.name+" color:"+cat2.color);
//4.拷貝繼承——將父類(lèi)的prototype的屬性和方法復(fù)制給子類(lèi)的prototype.
function extend2(parent,child){
var p = parent.prototype;
var c = parent.prototype;
for(var i in p){
c[i] = p[i];
}
c.uber = p;
}
extend2(Animal,Cat);
var cat3 = new Cat("zhong","black");
console.log("species:"+cat3.species+" name:"+cat3.name+" color:"+cat3.color);
參考來(lái)源:阮一峰博客