JavaScript适当的原型继承 [英] JavaScript proper prototypical inheritance
问题描述
我过去几个小时一直在研究原型继承,但我对如何应对这些问题留下了相互矛盾/不清楚的答案。我现在正在使用它似乎正常工作。
I've been spending my past couple hours researching prototypical inheritance, but I'm left with conflicting/unclear answers on how it should be done. It seems to be working for how I'm using it right now.
Paper.Component = function(){}; // useless unless I can solve problem mentioned below?
Paper.Component.prototype = {
isInBounds: function(x, y){
// ...
},
setPosition: function(x, y){
// ...
},
setSize: function(w, h){
// ...
}
};
Paper.Button = function(x, y, w, h, text){
// ...
}
Paper.Button.prototype = Object.create(Paper.Component.prototype);
它似乎还有另一个问题;我怎样才能 Paper.Button
将它的构造函数信息( x,y,w,h
)保存到 Paper.Component
而不是自己?即, Paper.Component
的每个孩子如何继承并设置这些值?
It also seems to have another problem; How can I have Paper.Button
save it's constructor information (x,y,w,h
) onto Paper.Component
rather than on itself? I.e., how can every child of Paper.Component
inherit and set these values?
推荐答案
到目前为止你做的很好。 按钮
中的缺失位如下所示:
What you have so far is fine. The missing bit in Button
looks like this:
Paper.Button = function(x, y, w, h, text){
Paper.Component.call(this, /*...any args required by it...*/);
// Button stuff here...
};
函数#call
调用函数具体的此
值以及您传递的任何参数。所以上面的调用 Paper.Component
从 Paper.Button
中调用这个
引用当前对象,并传递任何适当的参数。
Function#call
calls a function with a specific this
value and any arguments you pass it. So the above calls Paper.Component
from within Paper.Button
with this
referencing the current object, and passing along any appropriate arguments.
您还想设置构造函数
您替换的任何原型上的属性,而不仅仅是添加。它在很大程度上是可选的(JavaScript本身并没有使用构造函数
)但是由于JavaScript引擎将它设置在默认的原型对象上,我们应该在替换它们时设置它,所以我们与默认原型一致。
You also want to set the constructor
property on any prototype you replace rather than just adding to. It's largely optional (JavaScript itself doesn't use constructor
for anything), but since the JavaScript engine sets it on the default prototype objects, we should set it when replacing them, just so we're consistent with the default prototypes.
稍微简单,具体的例子:
Slightly simpler, concrete example:
function Shape(sides, color) {
this.sides = sides;
this.color = color;
}
// Shape.prototype.method = ...
function Rectangle(color) {
Shape.call(this, 4, color);
// Rectangle stuff here...
}
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle; // <== The constructor bit
// Rectangle.prototype.method = ...
如果您对使用JavaScript中的原型继承设置对象类的层次结构感兴趣,您可能需要查看我的 Lineage
帮助程序脚本,它使用更简单的语法自动执行上述操作并提供其他功能有用的功能。
If you're interested in setting up hierarchies of "classes" of objects using prototypical inheritance in JavaScript, you might want to look at my Lineage
helper script, which automates the above with a simpler syntax and provides other useful features.
这篇关于JavaScript适当的原型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!