7

我正在尝试以这种方式使用模块模式实现继承:

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

我错了什么?

4

2 回答 2

11

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

此外,您不能分配给this.prototype. 要创建所有实例都将从中继承的原型对象,您需要分配给构造函数prototype的属性(在您的情况下,关键字甚至指向全局对象)。thiswindow

并且您应该在获得 IIFE 后立即从 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;
})();
于 2013-03-15T16:07:39.550 回答
0
(function () {
    console.log("Child");
    Parent.call(this, arguments);
    this.prototype = Object.create(Parent.prototype);
})();

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

于 2013-03-15T15:51:24.997 回答