本文介绍了动态构造js函数名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以这种方式调用函数

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


推荐答案

你可以这样做:

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



您也可以将此与Jimmy的答案结合起来:


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

这篇关于动态构造js函数名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:44