javascript - 继承和模块模式

标签 javascript inheritance module-pattern

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

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)对象,您需要分配给 构造函数prototype 属性(this keyword 甚至指向全局 window 对象在你的情况下)。

而且你应该从 IIFE 中返回构造函数,而不是原型(prototype)对象。

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

关于javascript - 继承和模块模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15436533/

相关文章:

javascript - 优胜美地(OS X 10.10)上是否有javascript GUI自动化的引用

javascript - 有些 JS 加载,有些则不加载

c++ - 虚拟的,怎么用?

javascript - 如何将 JavaScript 代码库划分为模块?

javascript - 传递 jQuery 或不同全局的模块模式

javascript - 如何在 JavaScript 中通过滑动来跟踪链接?

javascript - 编译到 wwwroot 中的 Typescript 给出 "Duplicate identifier"错误

java - 通过父类(super class)对象的 ArrayList 访问子类方法?

mysql - 你能在 MySQL Workbench 中制作继承图吗?

Javascript 模块模式 - Object.create