0

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?

1
  • What are you trying to acheive? object[propertyname]() is the correct way of calling a function by name. Commented Apr 27, 2016 at 1:19

1 Answer 1

1

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

var obj = new window[type]();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.