问题描述
我正在浏览一个类似主题的讨论,但找不到我的情况...
我尝试调用带参数的父构造函数...可以
我有一个 PhysicsBody
超类,需要 aNode
作为其唯一的构造函数参数:
function PhysicsBody(aNode){
this.userData = aNode;
// ...
}
> PhysicsBody 继承了一个 DynamicBody
类。是构造函数也只需要 aNode
作为唯一的参数...就像我会在Java中做,我想调用等效于super aNode);
似乎找不到如何。
这里是 DynamicBody
class:
//想要new PhysicsBody(this,aNode),但是失败!
DynamicBody.prototype = new PhysicsBody();
DynamicBody.prototype.constructor = DynamicBody;
function DynamicBody(aNode){
//调用父构造函数失败:
// PhysicsBody.prototype.constructor.call(this,aNode);
// ...
}
一种方法:
function PhysicsBody(aNode){
this.userData = aNode;
}
PhysicsBody.prototype.pbMethod = function(){};
function DynamicBody(aNode){
PhysicsBody.call(this,aNode);
}
//设置继承
DynamicBody.prototype = Object.create(PhysicsBody.prototype);
DynamicBody.prototype.dbMethod = function(){};
b
$ bvar pb = new PhysicsBody('...');
实例
pb
获取userData
属性,并继承PhysicsBody.prototype
(pbMethod
当你执行
var db = new DynamicBody ..');
实例
db
获取userData
属性,并继承DynamicBody.prototype
(dbMethod
这个例子),它继承自PhysicsBody.prototype
。
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 takesaNode
as its only constructor argument:function PhysicsBody(aNode) { this.userData = aNode; // ... }
Of this
PhysicsBody
inherits aDynamicBody
class. Is constructor also takesaNode
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.Here's the
DynamicBody
class:// 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); //... }
解决方案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 auserData
property and also inherits the methods fromPhysicsBody.prototype
(pbMethod
in this case).When you do
var db = new DynamicBody( '...' );
the instance
db
gets auserData
property and also inherits the methods fromDynamicBody.prototype
(dbMethod
in this case), which in turn inherits fromPhysicsBody.prototype
.这篇关于继承父构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!