继承父构造函数参数 [英] Inherit parent constructor arguments

查看:53
本文介绍了继承父构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览类似主题的讨论,但找不到我的情况...

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.

我有一个 PhysicsBody 超类,它将 aNode 作为其唯一的构造函数参数:

I have a PhysicsBody superclass that takes aNode as its only constructor argument:

function PhysicsBody(aNode) {
    this.userData = aNode;
    // ...
}

这个PhysicsBody 继承了一个DynamicBody 类.构造函数是否也将 aNode 作为唯一参数......就像我在 Java 中所做的那样,我很想调用与 "super(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.

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

推荐答案

一种方法:

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( '...' );

实例 pb 获得一个 userData 属性,并从 PhysicsBody.prototype 继承方法(pbMethod in这种情况).

the instance pb gets a userData property and also inherits the methods from PhysicsBody.prototype (pbMethod in this case).

当你这样做

var db = new DynamicBody( '...' );

实例 db 获得一个 userData 属性,并从 DynamicBody.prototype 继承方法(dbMethod in这种情况下),它又继承自 PhysicsBody.prototype.

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.

这篇关于继承父构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆