JS-组合-实现继承

    // 父类
    function SuperType(){
        this.colors = ["red", "blue", "green"];
    }
    // 子类
    function SubType(){
        // 调用父类构造函数,实现继承
        SuperType.call(this);
    }
    // 两个子类实例,相互独立
    var instance1 = new SubType();
    instance1.colors.push("black");
    console.log(instance1.colors);    //"red,blue,green,black"
    var instance2 = new SubType();
    console.log(instance2.colors);    //"red,blue,green"
    // 父类
    function SuperType(name){
        this.name = name;
    }
    // 子类
    function SubType(){
        //通过 call 调用父类构造函数 - 实现继承
        SuperType.call(this, "Nicholas");
        // 扩展定义子类自己的属性
        this.age = 29;
    }
    // 实例对象
    var instance = new SubType();
    console.log(instance.name);    //"Nicholas";
    console.log(instance.age);     //29
    // 父类
    function SuperType(name){
        this.name = name;
        this.colors = ["red", "blue", "green"];
    }
    SuperType.prototype.sayName = function(){
        console.log(this.name);
    };
    // 子类中 call 父类 - 继承
    function SubType(name, age){
        SuperType.call(this, name);
        this.age = age;
    }
    // 原型继承 - 自己没有对应属性,会去父类查找
    SubType.prototype = new SuperType();
    // 子类的原型方法,不影响父类
    SubType.prototype.sayAge = function(){
        console.log(this.age);
    };
    // 继承自 父类,属性也一样
    var instance1 = new SubType("Nicholas", 29);
    instance1.colors.push("black");
    console.log(instance1);  //"red,blue,green,black"
    instance1.sayName();      //"Nicholas";
    instance1.sayAge();       //29
    // 两个子类实例,继承自一个父类,不会相互影响
    var instance2 = new SubType("Greg", 27);
    console.log(instance2.colors);  //"red,blue,green"
    instance2.sayName();      //"Greg";
    instance2.sayAge();       //27