面向对象的程序设计(六)组合继承

//组合继承(有时候也较伪经典继承):将原型链和借用构造函数的技术组合到一块
//思路:借用构造函数继承属性、原型链继承方法。避免了借用构造函数的原型方法不可复用,只有构造函数的属性可以复用的弊端
function SuperType(name) {
    this.name = name;
    this.colors = ["red", "blue"];
}

SuperType.prototype.sayName = function () {
    alert(this.name);
}

function SubType(name, age) {
    //继承了SuperType2同时还传递了参数
    SuperType.call(this, name);
    //SuperType2.apply(this, [name]);

    this.age = age;
}

SubType.prototype = new SuperType();

SubType.prototype.sayAge = function () {
    alert(this.age);
}

var instance1 = new SubType("Tom", "20");
instance1.colors.push("black");
alert(instance1.colors);
instance1.sayName();
instance1.sayAge();

var instance2 = new SubType("Lucy", "25");
alert(instance2.colors);
instance2.sayName();
instance2.sayAge();
原文地址:https://www.cnblogs.com/qiangspecial/p/3176402.html