继承

1.原型链

// 基本思想是利用原型让一个引用类型继承另一个引用类型的属性和方法 
     function SuperType () {
        this.superValue = true; 
    }

    SuperType.prototype.getSuperValue = function () {
        return this.superValue;
    }

    function SubType () {
        this.subValue = false;
    }
    // 继承SuperType
    SubType.prototype = new SuperType();

    SubType.prototype.getSubValue = function () {
        return this.subValue
    }

    var instance = new SubType();

    console.log(instance.getSuperValue()); // true

    // 这样会有一个问题,当SubType的一个实例改变了其中的一个属性,其所有的实例都被更改了这个属性

2.借用构造函数

    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"]

3.组合继承

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

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

    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('silva', 26);
    instance1.colors.push('black');
    console.log(instance1.colors)
    instance1.sayName();
    instance1.sayAge();

    var instance2 = new SubType('mike', 16);
    console.log(instance2.colors)
    instance2.sayName();
    instance2.sayAge();

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

4.寄生组合式继承

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

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

    function SubType (name, age) {
        // 继承属性
        SuperType.call(this, name);
        this.age = age;
    }

    // 继承方法
    SubType.prototype = new SuperType();
    // 修正constructor属性
    SubType.prototype.constructor = SubType;
    SubType.prototype.sayAge = function () {
        console.log(this.age);
    }

    var instance1 = new SubType('silva', 26);
    instance1.colors.push('black');
    console.log(instance1.colors)
    instance1.sayName();
    instance1.sayAge();

    var instance2 = new SubType('mike', 16);
    console.log(instance2.colors)
    instance2.sayName();
    instance2.sayAge();
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容