组合继承也叫伪经典继承,也就是组合了原型链和借用构造函数
实现思想:使用原型链实现对原型属性和方法的继承,通过借用构造函数实现对实例属性的继承,这样不仅可以在原型上定义方法,又能保证每个实例都有它自己的属性
- 创建超类构造函数Car
function Car(master,color){
this.master = master;
this.color = color;
}
# 原型链方法
Car.prototype.changeColor = function(color){
this.color = color;
}
- 创建子类构造函数Audi
function Audi(master,color,year){
Car.call(this,master,color);// 继承
this.year = year;// 购买年份
}
- 原型链继承以及构造函数指向设置(重点)
Audi.prototype = new Car();
Audi.prototype.constructor = Audi;// 设置原型的构造函数指向
- 子类构造函数设置原型链方法
Audi.prototype.getMessage = function(){
return this.master + "在" + this.year + "年买了一辆"+this.color+"的奥迪";
}
- 实例继承测试
var car1 = new Audi("car1Master","黑色","2016");
var car2 = new Audi("car2Master","白色","2017");
console.log(car1.getMessage());
// 结果:car1Master在2016年买了一辆黑色的奥迪
console.log(car2.getMessage());
// 结果:car2Master在2017年买了一辆白色的奥迪
使用超类构造函数的方法
car1.changeColor("红色");
car2.changeColor("蓝色");
console.log(car1.getMessage());
// 结果:car1Master在2016年买了一辆红色的奥迪
console.log(car2.getMessage());
// 结果:car2Master在2017年买了一辆蓝色的奥迪
网友评论