组合继承是指将原型链和借用构造函数组合到一块,发挥两者之长的继承模式。其中的思路是:使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实力属性的继承。这样既通过在原型上定义方法实现了函数复用,又能够每个实例有自己的属性。
function SuperType(name){
this.name=name; //定义属性
this.colors=["red","blue","green"]; //定义属性
}
SuperType.prototype.sayName=function(){
console.log(this.name) //SuperType原型上定义方法
}
function SubType(name,age){
SuperType.call(this,name);//继承属性
this.age=age; //定义自己的属性
}
SubType.prototype=new SuperType();//继承方法
SubType.prototype.constructor=SubType;//设置constructor的值
SubType.prototype.sayAge=function(){ //定义sayAge方法
console.log(this.age);
};
var instance1=new SubType("Nico",29);
instance1.colors.push("black");
console.log(instance1.colors);
instance1.sayAge();
instance1.sayName();
var instance2=new SubType("Sam",25);
console.log(instance2.colors);
instance2.sayAge();
instance2.sayName();
输出结果: