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);
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);
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);
ballFunctions['myNewFunction'] = function() { ... }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.
window object). Where is it defined? Inside another function? Most importantly, what is this in your context?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);
To avoid any modification to your existing code (which I assume is globally scoped) you can use this:
window[color + 'Ball'](this);