Jem
Jem

Reputation: 6406

JS, prototype: Having a constructor, how can I get an instance?

A model in my code receives a constructor at some point:

this.defaultView = WJCard;

WJCard is a simple prototype:

function WJCard() {...}

At some point, the model needs to create a WJCard instance based on the this.defaultView property. I thought the following would help, but I'm wrong:

WJModel.prototype.render = function(classname) {

if (classname) {
    this.view = this.defaultView.call(); // Returns null :(
    // ...
}

    /. ...

}

I've tried a bit of everything with no success. Can anybody help me?


Corrected code thanks to answer...

WJModel.prototype.render = function(classname) {

if (classname) {
    this.view = new classname(); // works fine this way!
    // ...
}

    /. ...

}

Upvotes: 0

Views: 51

Answers (1)

Ry-
Ry-

Reputation: 224913

You can still use new as usual:

this.view = new this.defaultView();

Upvotes: 3

Related Questions