Javascript继承设计问题
以下代码片段显示了我如何创建继承。我受到这篇文章的启发。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,这是一个糟糕的继承模式。如果父构造函数需要传递参数怎么办?
子类的原型应该继承父类的原型,而不是它的实例。一些库是这样实现的:
用作:
然后在子级的构造函数中,您必须调用父级的构造函数:
当然,如果您愿意,您也可以添加一个
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:
Used as:
Then in the child's constructor function, you have to call the parents constructor function:
Of course you can also add a
superclass
property if you wanted to.