继承和模块模式

Web*_*man 7 javascript inheritance module-pattern

我试图用这种方式用模块模式实现继承:

Parent = function () {

    //constructor
    (function construct () {
        console.log("Parent");
    })();

    // public functions
    return this.prototype = {

        test: function () {
            console.log("test parent");
        },


        test2: function () {
            console.log("test2 parent");
        }

    };
};


Child = function () {

    // constructor
    (function () {
        console.log("Child");
        Parent.call(this, arguments);
        this.prototype = Object.create(Parent.prototype);
    })();


    // public functions
    return this.prototype = {

        test: function()
        {
            console.log("test Child");
        }

    }

};
Run Code Online (Sandbox Code Playgroud)

但是我不能从孩子的实例那里打来电话test2().

var c = new Child();
c.test2(); // c.test2 is not a function
Run Code Online (Sandbox Code Playgroud)

我错了什么?

Ber*_*rgi 11

您没有以正确的方式使用模块模式.不知何故,您的"构造函数"被称为立即调用的函数表达式(IIFE),而模块闭包不是.它应该是反过来的.

此外,您无法分配this.prototype.要创建所有实例将从其继承的原型对象,您需要分配构造函数prototype属性(该关键字甚至指向您案例中的全局对象).thiswindow

并且你应该尽快从IIFE返回构造函数,而不是原型对象.

Parent = (function () {
    // constructor
    function construct () {
        console.log("Parent");
    };

    // public functions
    construct.prototype.test = function () {
        console.log("test parent");
    };
    construct.prototype.test2 = function () {
        console.log("test2 parent");
    };

    return construct;
})();


Child = (function () {
    // constructor
    function construct() {
        console.log("Child");
        Parent.apply(this, arguments);
    }

    // make the prototype object inherit from the Parent's one
    construct.prototype = Object.create(Parent.prototype);
    // public functions
    construct.prototype.test = function() {
        console.log("test Child");
    };

    return construct;
})();
Run Code Online (Sandbox Code Playgroud)

  • 取决于你对"静态"的意思,在动态JS语言中没有真正的等价:-)但是,你可以为`Child`构造函数对象分配一个函数:`Child.method = function(){... `;(或在模块闭包内,`construct.method = ...;`) (2认同)