Inheritance and module pattern

后端 未结 2 1230
傲寒
傲寒 2020-12-15 01:15

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

Parent = function () {

    //constructor
    (function construct () {
                 


        
相关标签:
2条回答
  • 2020-12-15 02:00

    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;
    })();
    
    0 讨论(0)
  • 2020-12-15 02:04
    (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.

    0 讨论(0)
提交回复
热议问题