【面向对象的程序设计(5)】组合继承(伪经典继承)

基本思想

将原型链和借用构造函数的技术组合到一块。
使用原型链实现对原型属性和方法的继承,通过借用构造函数实现对实例属性的继承。

function SuperType(name){
    this.name = name;
    this.colors = ["red","blue","green"];
}

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

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

    //实例属性
    this.age = age;
}
//继承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function () {
    alert(this.age);
};

var instance1 = new SubType("Wonder",23);
instance1.colors.push("black");
alert(instance1.colors);      //red,blue,green,black
instance1.sayName();          //Wonder      
instance1.sayAge();           //23

var instance2 = new SubType("Abby",29);
alert(instance2.colors);      //red,blue,green
instance2.sayName();          //Abby
instance2.sayAge();           //29

组合继承是JS最常用的继承模式。

你可能感兴趣的:(【面向对象的程序设计(5)】组合继承(伪经典继承))