Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

javascript - 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:

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);
    //...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

image


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.

image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...