前端杂货随记

javascript继承之组合继承(三)

2018-02-04  本文已影响0人  程序蜗牛

组合继承也叫伪经典继承,也就是组合了原型链和借用构造函数
实现思想:使用原型链实现对原型属性和方法的继承,通过借用构造函数实现对实例属性的继承,这样不仅可以在原型上定义方法,又能保证每个实例都有它自己的属性

function Car(master,color){
    this.master = master;
    this.color = color;
}
# 原型链方法
Car.prototype.changeColor = function(color){
    this.color = color;
}
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年买了一辆蓝色的奥迪
上一篇 下一篇

猜你喜欢

热点阅读