在 javascript 中根据输入的字符串调用对应的函数?
阿神
阿神 2017-04-10 14:41:07
0
2
391

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

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

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

阿神
阿神

闭关修行中......

reply all(2)
左手右手慢动作

比如你有一个对象

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');
Peter_Zhu
var functionMap = {
  handle_hello: function() {
  },
  handle_world: function() {
  }
};

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

callFunction(functionMap, "hello");

是这样吗?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template