【问题标题】:Inheritance and module pattern继承和模块模式
【发布时间】:2023-03-21 19:10:01
【问题描述】:

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

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

我做错了什么?

【问题讨论】:

标签: javascript inheritance module-pattern


【解决方案1】:

您没有以正确的方式使用模块模式。不知何故,您的“构造函数”被称为立即调用的函数表达式(IIFE),而模块闭包则不是。应该是反过来的。

另外,您不能分配给this.prototype。要创建所有实例都将继承的原型对象,您需要分配给 构造函数prototype 属性(this keyword 甚至指向您的全局 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;
})();

【讨论】:

  • 非常感谢。现在我还有一个问题:是否可以在 Child 中添加静态函数?
  • 取决于你所说的“静态”,在动态 JS 语言中没有真正的等价物:-) 但是,你可以将一个函数分配给 Child 构造函数对象:@987654329 @(或在模块闭包内,construct.method = …;
  • 带有“静态”我的意思是调用一个函数而不创建一个Child的实例。像这样Child.myStaticFunction()
  • 不清楚为什么这条线 :Parent.apply(this, arguments); 在那里。它在相关代码中什么都不做。
  • @RoyiNamir:它确实执行了父构造函数,从副作用console.log("Parent"); 可以看出。当然,它实际上什么也没做,但它的存在是为了防止父级在未来得到扩展。只是保持代码可维护性的一个好习惯,它没有害处:-)
【解决方案2】:
(function () {
    console.log("Child");
    Parent.call(this, arguments);
    this.prototype = Object.create(Parent.prototype);
})();

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

【讨论】:

  • 谁将this 传递为this
  • 你说“pass this as argument”,这似乎没用。好的,我假设您将它作为 thisArg 传递,但即使不是也没关系 - 您能否发布您想到的代码?
  • (function (that) { Parent.call(that ... } (this))
  • 啊,现在我明白了。我什至没有发现 Parent 调用是大错误,而是 this.prototype 分配。
猜你喜欢
  • 1970-01-01
  • 2016-06-24
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 2015-02-09
  • 2013-05-15
  • 1970-01-01
  • 2012-01-30
相关资源
最近更新 更多