MCMastery
MCMastery

Reputation: 3249

Javascript call function from function name

I need to call a function, given its name as a string. This is what I have so far:

var obj = window[type]();

Type is the string. I am testing it with the function Wall():

Wall.prototype = new GameObject();
Wall.prototype.constructor = Wall;
function Wall() {
    this.bounds.width = 50;
    this.solid = true;
    this.bounds.height = 50;
    this.layer = 1;
    this.bounds.setCenter(engine.gameView.center().add(75, 75));
    this.render = function() {
        engine.gameView.fillRect(this.bounds, new Color(0, 0, 0));
    };
}

GameObject is a class it "extends". When I just use new Wall() normally, (not with reflection), it works fine. But if I use the reflection, it will output the Wall as being a Window (as I saw with console.log in its constructor). When I call it without reflection, it outputs it as being a Wall. Because it says it is a Window when using reflection, it says bounds is undefined, since that is a property of GameObject. What can I do to fix this?

Upvotes: 0

Views: 225

Answers (1)

abelman001
abelman001

Reputation: 26

You need the "new" keyword when you call a constructor. I.e.,

var obj = new window[type]();

Upvotes: 1

Related Questions