Inheritance and module pattern

落花浮王杯 提交于 2019-12-18 01:19:27

问题


I'm trying to implement the inheritance with the module pattern in this way:

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

    }

};

but I can't to call from child's instance the test2().

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

What I wrong?


回答1:


You're not using the module pattern in the correct way. Somehow, your "constructor" is called as an immediately-invoked function expression (IIFE), and the module closure is not. It should be the other way round.

Also, you can't assign to this.prototype. To create the prototype object from which all instances will inherit, you will need to assign to the prototype property of the constructor function (the this keyword even pointed to the global window object in your case).

And you should return the constructor function, not the prototype object, from the IIFE as soon as you have it.

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;
})();



回答2:


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

this refers to window, because you wrapped your code into a function. Remove the wrapping function or pass this as argument.



来源:https://stackoverflow.com/questions/15436533/inheritance-and-module-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!