简体   繁体   English

继承父构造函数参数

[英]Inherit parent constructor arguments

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. 其中PhysicsBody继承了DynamicBody类。 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"); 构造函数也将aNode作为唯一参数...就像我在Java中这样做,我喜欢称之为"super(aNode"); Can't seem to find out how. 似乎无法弄清楚如何。

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);
    //...
}

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.prototypepbMethod在这种情况下)。


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

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)将在内部为DynamicBody实例调用PhysicsBody(1, 2, 3)

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM