【问题标题】:Abstract way to call functions with javascript. Can it be done?用 javascript 调用函数的抽象方法。可以做到吗?
【发布时间】:2016-03-13 02:54:17
【问题描述】:

是否可以在javascript中通过使用字符串参数指定需要调用的函数名来有条件地调用函数?

function test1(){
    // something
}

function test2(){
   // Something
}
function test3(){
   // something
}
var callString = 'test1' // test1 or test2 or test3

callString();
/* Obviously this is an error, but
coul this be formatted so that JS,
could call the function of callString?*/

【问题讨论】:

标签: javascript performance function user-defined-functions


【解决方案1】:

当然,如果你的结构合理的话。您可以使用类数组(或括号)表示法:

var functions = {
    test1: function () {},
    test2: function () {},
    test3: function () {}
}

var callString = 'test1';
functions[callString](); // run functions.test1()

callString = 'test2';
functions[callString](); // run functions.test2()

【讨论】:

    【解决方案2】:

    如果functionsglobal context 中,则每个global functionglobal variable 都是keywindow 对象。

    function test1() {
      alert('Hi!');
    }
    
    function test2() {
      alert('Hi!');
    }
    
    function test3() {
      alert('Hi!');
    }
    var callString = 'test1';
    
    window[callString]();

    【讨论】:

      猜你喜欢
      • 2013-01-21
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多