继承和模块模式

Inheritance and module pattern

本文关键字:模式 模块 继承      更新时间:2023-09-26

我正试图通过以下方式实现模块模式的继承:

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

我错了什么?

您没有以正确的方式使用模块模式。不知怎的,您的"构造函数"被调用为一个立即调用的函数表达式(IIFE(,而模块闭包不是。应该是反过来。

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

一旦有了它,就应该从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;
})();
(function () {
    console.log("Child");
    Parent.call(this, arguments);
    this.prototype = Object.create(Parent.prototype);
})();

this指的是window,因为您将代码封装到了一个函数中。删除包装函数或将this作为参数传递。