【问题标题】:Dynamic function call in JavaScriptJavaScript 中的动态函数调用
【发布时间】:2021-07-06 12:16:13
【问题描述】:

有没有更好的方法来动态地做到这一点:

function abcKY(a, no) {
  console.log(a + no);
}
function abcBC(a, no) {
  console.log(a - no);
}
var result_from_db = "abcKY";

eval(result_from_db)(1, 2);

我有多个不同的要求,我希望标准化,使其可配置。所以有一个动态的函数调用会很有帮助。

【问题讨论】:

    标签: javascript function dynamic eval


    【解决方案1】:

    您可以将对象函数映射作为键函数放入内部,并使用变量result_from_db 调用它。检查这个:

    var functions = {};
    functions.abcKY = function(a, no) {
      console.log(a + no);
    };
    functions.abcBC = function(a, no) {
      console.log(a - no);
    };
    var result_from_db = "abcKY";
    functions[result_from_db](1, 2);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      • 2015-07-30
      • 2010-10-08
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多