JS 面向对象之继承--多种组合继承

转自 http://www.cnblogs.com/yangjinjin/archive/2013/02/01/2889563.html

这一次要讲 组合、原型式、寄生式、寄生组合式继承方式。

1. 组合继承:又叫伪经典继承,是指将原型链和借用构造函数技术组合在一块的一种继承方式。

下面来看一个例子:

    function SuperType(name) {
        this.name = name;
        this.colors = ["red", "blue", "green"];
    }
    SuperType.prototype.sayName = function() {
        alert(this.name);
    }
    function SubType(name, age) {
        SuperType.call(this, name);
        this.age = age;
    }

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

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

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

组合继承避免了原型链和借用构造函数的缺陷,融合它们的优点。

未完待续……

原文地址:https://www.cnblogs.com/SherryIsMe/p/4343162.html