繼承的幾種實現(xiàn)方式:原型鏈眷蚓、借用構(gòu)造函數(shù)鼻种、組合繼承、原型式繼承沙热、寄生式繼承叉钥、寄生組合式繼承;
繼承的實現(xiàn)篙贸,一般有接口繼承和實現(xiàn)繼承投队。JavaScript只支持實現(xiàn)繼承,其主要依靠原型鏈來實現(xiàn)爵川。
一敷鸦、原型鏈
其主要思想是利用原型讓一個引用類型繼承另一個引用類型的屬性和方法。
案例:
function SuperType(){
this.property = true;
this.colors = ["red","blue","green"]
}
SuperType.prototype.getSuperValue = function(){
return this.property;
};
function SubType(){
this.subproperty = false;
}
//繼承了SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function(){
return this.subproperty;
};
var instance = new SubType();
console.log(instance.getSuperValue());
console.log( instance instanceof Object);//true
console.log(instance instanceof SuperType);//true
console.log(instance instanceof SubType);//true
//遇到的問題:一寝贡、引用類型值的原型屬性會被所有實例共享扒披;
//二,在創(chuàng)建子類型實例時兔甘,不能向超類型的構(gòu)造函數(shù)中傳遞參數(shù)谎碍;
instance1.colors.push("black");
var instance2 = new SubType();
console.log(instance2.colors);
二、借用構(gòu)造函數(shù)
為了解決上面的問題洞焙,出現(xiàn)了借用構(gòu)造函數(shù)的方式蟆淀,通過使用apply和call方法在將來新創(chuàng)建的對象上執(zhí)行構(gòu)造函數(shù);
function SuperType(name){
this.colors = ["red","blue","green"];
this.name = name;
}
function SubType(){
//繼承了SuperType方法,同時還傳遞了參數(shù)
SuperType.call(this,"Jack");
//實例屬性
this.age = 29;
}
var instance1 = new SubType();
instance1.colors.push("black");
console.log(instance1.colors);//"red","blue","green","black"
var instance2 = new SubType();
console.log(instance1.colors);//"red","blue","green"
這種方式解決了傳遞參數(shù)的問題澡匪,同時讓每個實例用于自己的私有引用類型熔任;但同時造成另一個問題,就是無法實現(xiàn)函數(shù)復用唁情,即超類型的原型中定義的方法疑苔,對子類型而言都不可繼承。
三甸鸟、組合繼承
指將原型鏈和借用構(gòu)造函數(shù)技術(shù)組合在一塊使用惦费。使用原型鏈實現(xiàn)對原型屬性和方法的繼承,而通過借用構(gòu)造函數(shù)來實現(xiàn)對實例屬性的繼承抢韭。既通過在原型上定義方法實現(xiàn)函數(shù)復用薪贫,又保證每個實例都有它自己的屬性。
function SuperType(name){
this.name = name;
this.colors = ["red","blue","green"];
}
SuperType.prototype.sayName = function(){
console.log(this.name);
};
function SubType(name,age){
//繼承實例屬性
SuperType.call(this.name);
this.age = age;
}
//繼承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
console.log(this.age);
};
var instance1 = new SubType("Tom",29);
instance1.colors.push("black");
console.log(instance1.colors);
instance1.sayName();
console.log(instance1 instanceof SubType); //true
var instance2 = new SubType("Jack",29);
console.log(instance2.colors);
instance2.sayName();
四刻恭、原型式繼承
其思想是瞧省,借助原型基于已有的對象創(chuàng)建新的對象,同時不必因此創(chuàng)建自定義類型
function object(o){
function F(){};
F.prototype = o;
return new F();
}
var person = {
name:"Jack",
friends:["xiaomi","vivo","oppo"]
};
var anotherPerson = object(person);
anotherPerson.name = "Lily";
anotherPerson.friends.push("Tom");
var yetAnotherPerson = object(person);
yetAnotherPerson.name = "Andy";
yetAnotherPerson.friends.push("Mary");
console.log(person.friends);//"xiaomi", "vivo", "oppo", "Tom", "Mary"