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 を取得したらすぐに、プロトタイプ オブジェクトではなく、コンストラクター関数を返す必要があります。

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 に答える