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

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

问题描述

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



我尝试调用带参数的父构造函数...可以



我有一个 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
$ b

  var 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 takes aNode as its only constructor argument:

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.

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 a userData property and also inherits the methods from PhysicsBody.prototype (pbMethod in this case).


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.

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

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