JavaScript 继承 3 组合继承

组合继承,有时候也叫做伪经典继承,指的是将原型链和借用构造函数的技术组合到一起,从而发挥二者之长的一种继承模式。其背后的思路是使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。这样,既通过在原型上定义方法实现了函数复用,又能够保证每个实例都有它自己的属性:

        function SuperColors(colorName) {
            if (typeof colorName != "undefined") {
                this.colors = ["red", "green", "blue", colorName];
            } else {
                this.colors = ["red", "green", "blue"];
            }
        }
        SuperColors.prototype.sayColors = function () {
            console.log(this.colors);
        };
        function SubColors(colorName, level) {
            // 继承属性
            SuperColors.call(this, colorName);

            this.level = level;
        }

        SubColors.prototype = new SuperColors();

        SubColors.prototype.sayLevel = function () {
            console.log(this.level);
        };

        var instance1 = new SubColors("gray", 0);
        instance1.colors.push("white");
        instance1.sayColors();
        instance1.sayLevel();

        var instance2 = new SubColors("black", 1);
        instance2.sayColors();
        instance2.sayLevel();

上述代码输出结果:

输出结果

上述代码,可以让两个不同的 SubColors 实例既分别拥有自己的属性 —— 包括 colors 属性,又可以使用相同的方法。

组合继承避免了原型链和借用构造函数的缺陷,融合了它们的优点,成为 JavaScript 中最常用的继承模式。而且,instanceof 和 isPrototypeof 也能够用于识别基于组合继承创建的对象。

你可能感兴趣的:(JavaScript 继承 3 组合继承)