1

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);
0

4 Answers 4

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

and you can do ballFunctions['myNewFunction'] = function() { ... }
5

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.

1 Comment

@jarn: Well, that error means that 'redBall' is not a function in the global namespace (i.e. on the window object). Where is it defined? Inside another function? Most importantly, what is this in your context?
4

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

5 Comments

Functions that do everything aren't that great of a practice either.
I would still say dynamic function names are a bad way to implement the logic there. A switch statement with other function calls or perhaps a method like Rfvgyhn (that's hard to type) suggested is going to produce much more maintainable code.
I really have to agree --- there's no way you have to do something this ugly.
@jarn: JavaScript is not PHP, trying to write PHP in JavaScript will only lead to an ugly mess. Doing this sort of thing is a bad idea so there's no good reason that it should be easy anywhere.
@mu And honestly, doing that in PHP makes me nervous too. Just because it's easy doesn't make it a good practice.
1

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

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

1 Comment

You're gonna have to show more code, then, and some which reflects actual context.

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.