admin管理员组文章数量:1326036
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);
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);
Share
Improve this question
edited Apr 9, 2011 at 1:56
jarn
asked Apr 9, 2011 at 1:17
jarnjarn
2631 gold badge2 silver badges8 bronze badges
0
4 Answers
Reset to default 5You 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 bine 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);
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.
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);
本文标签: javascriptconstructing js function name dynamicallyStack Overflow
版权声明:本文标题:javascript - constructing js function name dynamically - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742119709a2421638.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论