首页 > 在 javascript 中根据输入的字符串调用对应的函数?

在 javascript 中根据输入的字符串调用对应的函数?

用户输入一个字符串(其实是函数的名字), 根据这个字符串调用对应的函数.

例如 输入 "hello"
调用 handle_hello 函数.

想做一个名字和函数的列表, 可是函数又不能做成指针, 怎么办?
而且存成什么格式 json? 数组?


var functionMap = {
  handle_hello: function() {
  },
  handle_world: function() {
  }
};

var callFunction = function(obj, functionName) {
  obj["handle" + functionName]();
};

callFunction(functionMap, "hello");

是这样吗?


比如你有一个对象

var methods = {
    method1:function(){
        console.log('show me');
    },
    method2:function(){
        console.log('show me 2');
    }
}

//你可以这样执行他们,把函数名字做为一个字符串

methods['method1'](); //等同 methods.method1();
methods['method2'](); //等同 methods.method2();

如上,你就可以传字符串来执行函数了

var callFunction = function(methods,methodname){
     if(typeof methods[methodname] === 'function'){
         methods[methodname]();
     }
}
//todo
callFunction(methods,'method1');
【热门文章】
【热门文章】