javascript 继承父构造函数参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7785955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inherit parent constructor arguments
提问by Jem
I'm browsing the discussion for a similar topic, but can't find my situation...
我正在浏览类似主题的讨论,但找不到我的情况...
Am trying call parent constructors with parameters... can't seem to get it right.
我正在尝试使用参数调用父构造函数...似乎无法正确处理。
I have a PhysicsBody
superclass that takes aNode
as its only constructor argument:
我有一个PhysicsBody
超类,它aNode
作为它唯一的构造函数参数:
function PhysicsBody(aNode) {
this.userData = aNode;
// ...
}
Of this PhysicsBody
inherits a DynamicBody
class. Is constructor also takes aNode
as only argument... Like I would do it in Java, I'd love to call something equivalent to "super(aNode");
Can't seem to find out how.
其中PhysicsBody
继承了一个DynamicBody
类。构造函数是否也aNode
作为唯一的参数......就像我在 Java 中所做的那样,我很想调用与"super(aNode");
无法找到方法等效的东西。
Here's the DynamicBody
class:
这是DynamicBody
课程:
// Wanted to give "new PhysicsBody(this, aNode)", but that fails!
DynamicBody.prototype = new PhysicsBody();
DynamicBody.prototype.constructor=DynamicBody;
function DynamicBody(aNode) {
// calling the parent constructor fails too:
// PhysicsBody.prototype.constructor.call(this, aNode);
//...
}
回答by ?ime Vidas
One way to do it:
一种方法:
function PhysicsBody( aNode ) {
this.userData = aNode;
}
PhysicsBody.prototype.pbMethod = function () {};
function DynamicBody( aNode ) {
PhysicsBody.call( this, aNode );
}
// setting up the inheritance
DynamicBody.prototype = Object.create( PhysicsBody.prototype );
DynamicBody.prototype.dbMethod = function () {};
Now, when you do
现在,当你做
var pb = new PhysicsBody( '...' );
the instance pb
gets a userData
property and also inherits the methods from PhysicsBody.prototype
(pbMethod
in this case).
该实例pb
获取一个userData
属性,并从PhysicsBody.prototype
(pbMethod
在这种情况下)继承方法。
When you do
当你做
var db = new DynamicBody( '...' );
the instance db
gets a userData
property and also inherits the methods from DynamicBody.prototype
(dbMethod
in this case), which in turn inherits from PhysicsBody.prototype
.
该实例db
获取一个userData
属性,并从DynamicBody.prototype
(dbMethod
在本例中)继承方法,后者又从PhysicsBody.prototype
.
回答by pimvdb
If I understand you correctly, by saying you want to inherit the parent constructor arguments, you mean that new DynamicBody(1, 2, 3)
will internally call PhysicsBody(1, 2, 3)
for the DynamicBody
instance.
如果我理解正确的话,说要继承父构造函数的参数,你的意思是new DynamicBody(1, 2, 3)
将内部调用PhysicsBody(1, 2, 3)
的DynamicBody
实例。
This can be accomplished by using .apply
and passing arguments
along: http://jsfiddle.net/pmkrQ/.
这可以通过使用.apply
和传递arguments
:http: //jsfiddle.net/pmkrQ/来完成。
function DynamicBody() {
PhysicsBody.apply(this, arguments);
}