继承和模块模式

时间:2013-03-15 15:43:54

标签: 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");
        }

    }

};

但我无法从孩子的实例test2()拨打电话。

var c = new Child();
c.test2(); // c.test2 is not a function

我错了什么?

2 个答案:

答案 0 :(得分:11)

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

此外,您无法分配到this.prototype。要创建所有实例将从其继承的原型对象,您需要分配构造函数prototype属性(this keyword甚至指向全局{{在你的情况下1}}对象。)

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

window

答案 1 :(得分:0)

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

this引用window,因为您将代码包装到函数中。删除包装函数或传递this作为参数。