jarn
jarn

Reputation: 263

constructing js function name dynamically

I want to call a function this way

redBall(this);

but I want to dynamically construct from a string. I tried something like this but it's not working.

var color = 'red';
color+'Ball'(this);

Upvotes: 1

Views: 976

Answers (4)

Chris
Chris

Reputation: 4471

You could do something like this:

var ballFunctions = {
    redBall: function(obj) {
        alert("Hi, I'm a red ball");
    },
    blueBall: function(obj) {
        alert("Hi, I'm a blue ball");
    }
};

color = "red";
ballFunctions[color + "Ball"](this);
color = "blue";
ballFunctions[color + "Ball"](this);


You could also combine this with Jimmy's answer and do:

function ball(color, obj) {
    ballFunctions[color + "Ball"](obj);

    // Or use the window object if your funcs are in the global namespace like Cameron said
    // window[color + "Ball"](obj);
}

color = "red";
ball(color, this);

Upvotes: 5

Cameron
Cameron

Reputation: 98886

Subscript the implicit window object:

window[color + 'Ball'](this)

Your example was attempting to call the string 'Ball' (which doesn't make sense since strings aren't callable), then concatenate the result with color -- not quite what you wanted.

Upvotes: 5

JAAulde
JAAulde

Reputation: 19560

To avoid any modification to your existing code (which I assume is globally scoped) you can use this:

window[color + 'Ball'](this);

Upvotes: 1

Jimmy Sawczuk
Jimmy Sawczuk

Reputation: 13614

Dynamically named functions aren't a great practice. What about this?

function Ball(color, object)
{ 
     // do stuff
}

And then call it via: Ball('red', this);

Upvotes: 4

Related Questions