Resig的JS继承脚本...父类的属性被覆盖
只是尝试在某处使用 JS 继承,并且遇到了子类覆盖属性的问题。 我使用一个名为 options 的对象来具有可以覆盖的默认属性。就像这样:
class a {
options: {
property1: 1,
property2: 2
},
init: function (parameters, element) {
this.options = $.extend({}, this.options, parameters);
}
}
我这样做是因为我也使用插件创建......但这不是问题。问题是,当您覆盖也有选项参数的基类时,它会被覆盖,并且当您在基类中调用 _super 时,它不知道它用来做什么来执行它需要做的事情做。
例如,您有两个类:Person
和 Ninja
。在 Person
初始化后,他吃东西……他饿了。 Ninja
扩展了 Person
并且他需要读取命中列表。虽然是忍者,但作为人还是要吃饭的。所以你调用 this._super();但他似乎不再有任何食物了(这是在选项中声明的)。
这是一个小提琴,您可以在其中明白我的意思: http://jsfiddle.net/37Z8m/5/
我能想到的解决这个问题的方法是重新声明父类中的默认选项,以便它们仍然存在,或者向 J-Resig 的继承脚本添加一个例外,以仅添加到选项类而不覆盖它...只不过在其他语言中,当你扩展时,它仍然可以访问它自己的属性。
John 的继承脚本首先覆盖该对象,然后让您调用 _super();我认为这是错误的......?
was just attempting to use JS Inheritance somewhere and have come across a problem with the subclass overwriting properties.
I use an object called options to have default properties that can be overridden. So like so:
class a {
options: {
property1: 1,
property2: 2
},
init: function (parameters, element) {
this.options = $.extend({}, this.options, parameters);
}
}
I do it this way because I also use plugin creation... but that's not the problem. The issue is that when you over-ride the base class that also has an options parameter, then it is overwritten and when you call _super in the base class, then it doesn't know what it used to anymore to do what it needs to do.
For example, you have two classes: Person
and Ninja
. Upon initialisation of Person
he eats... hes hungry. Ninja
extends Person
and he needs to read a hit list. Even though hes a ninja, he still needs to eat as a Person. So you call this._super(); but he doesn't seem to have any food anymore (which is declared in the options).
Here's a fiddle where you can see what I mean: http://jsfiddle.net/37Z8m/5/
The ways I can think of to get around this is to either redeclare the default options that are inside the parent class so they still exist or add an exception to J-Resig's inheritance script to only add to an options class and not override it... It's just that in other languages when you extend, it still has access to it's own properties.
John's inheritance script first overrides the object and then lets you call _super(); which I think is wrong...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
但是,如果您想要覆盖父选项而不是合并怎么办?听起来你应该直接使用选项而不使用中间字典:
变成
But what if you wanted to override the parent options instead of merging? Sounds like you should just use the options directly without the intermediate dictionary:
becomes