组合继承有时候也叫做为经典继承,指的是将原型链和借用构造函数的技术组合到一起,发挥二者之长。背后的思路是使用原型链实现方式对原型属性和方法的继承,而借用构造函数来实现对实例属性的继承。
查看案例(高程三):
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;//sub使用的
}
//继承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
//输出SubType自己的
console.log(this.age);
};
var instance1 = new SubType("这里是instance1",29);
instance1.colors.push("black");//添加color
console.log(instance1.colors);
instance1.sayName();
instance1.sayAge();
var instance2 = new SubType("这里是instance2",30);
console.log(instance2.colors);
instance2.sayName();
instance2.sayAge();
控制台会输出
["red", "blue", "green", "black"]
,这里是instance1
,29
["red", "blue", "green"]
,这里是instance2
,30
这样就可以让两个不同的SubType实例分别拥有自己的属性,包括color属性,还能够使用相同的方法