最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - constructing js function name dynamically - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 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 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);
发布评论

评论列表(0)

  1. 暂无评论