Javascript继承设计问题

发布于 2024-12-10 20:46:39 字数 804 浏览 0 评论 0原文

以下代码片段显示了我如何创建继承。我受到这篇文章的启发。

function Base() {
    this.init();
}

Base.prototype.init = function () {
};

Derived1.prototype = new Base();
Derived1.prototype.constructor = Derived1;
Derived1.superclass = Base.prototype;

function Derived1() {    
}

Derived1.prototype.init = function() {
    Derived1.superclass.init.call(this);
};

Derived2.prototype = new Derived1();
Derived2.prototype.constructor = Derived2;
Derived2.superclass = Derived1.prototype;

function Derived2() {
    Derived2.superclass.init.call(this);
}

当浏览器加载此 js 文件时,将调用所有构造函数。

Derived2.prototype = new Derived1();

这可能会导致一些意外的行为。

有什么办法可以阻止这种行为吗?

The following snippet shows how I created my inheritance. I got inspired by this article.

function Base() {
    this.init();
}

Base.prototype.init = function () {
};

Derived1.prototype = new Base();
Derived1.prototype.constructor = Derived1;
Derived1.superclass = Base.prototype;

function Derived1() {    
}

Derived1.prototype.init = function() {
    Derived1.superclass.init.call(this);
};

Derived2.prototype = new Derived1();
Derived2.prototype.constructor = Derived2;
Derived2.superclass = Derived1.prototype;

function Derived2() {
    Derived2.superclass.init.call(this);
}

When this js file is loaded by the browser all the contructors will be called.

Derived2.prototype = new Derived1();

This can lead to some unexpected behaviour.

Is there any way to stop this behaviour ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

因为看清所以看轻 2024-12-17 20:46:39

在我看来,这是一个糟糕的继承模式。如果父构造函数需要传递参数怎么办?

子类的原型应该继承父类的原型,而不是它的实例。一些库是这样实现的:

function inherit(Child, Parent) {
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}

用作:

inherit(Derived1, Base);

然后在子级的构造函数中,您必须调用父级的构造函数:

function Child() {
    Parent.call(this);
}

当然,如果您愿意,您也可以添加一个 superclass 属性。

Imo this is a bad inheritance pattern. What if the parent constructor function expects parameters to be passed?

The prototype of the child class should inherit from the prototype of the parent class, not an instance of it. Several libraries implement this way:

function inherit(Child, Parent) {
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}

Used as:

inherit(Derived1, Base);

Then in the child's constructor function, you have to call the parents constructor function:

function Child() {
    Parent.call(this);
}

Of course you can also add a superclass property if you wanted to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文