【问题标题】:inherit sub-object together with object与对象一起继承子对象
【发布时间】:2014-06-18 08:54:08
【问题描述】:

我正在使用对象 AA.B

A.myB = A.B;

我有一个继承的A1A1.B,其中A1.B 继承自A.B

A1.myB = A1.B;

实现这一点的代码如下所示:

A = function() {
    this.myB = this.createB();
};
...
A.prototype.createB = function() {
    return new A.B();
};

然后在继承 A 我需要更改 .createB:

A1.prototype.createB = function() {
    return new A1.B1();
};

我想我忽略了一些东西 - 有没有更直接的方法来设置它,而无需更改 createB

【问题讨论】:

    标签: javascript inheritance constructor prototype


    【解决方案1】:

    好的,在写这篇文章时,我找到了答案。也许对那里的任何人都有帮助:

    A.prototype.createB = function() {
        return new this.constructor.B();
    };
    

    我认为这应该可以解决问题,并且与被定义为主对象构造函数的属性的子对象结合起来可能会非常方便。

    【讨论】:

    • 唯一的缺点似乎是每个继承的 A 都必须定义其继承的 B。我接受我的答案,但会接受另一个更好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2019-07-29
    • 1970-01-01
    • 2012-01-05
    • 2011-10-08
    • 1970-01-01
    • 2013-10-15
    相关资源
    最近更新 更多