Calling a javascript function with a string?
I have a function:
var greet = function (name) {
console.log("Hi " + name);
}
If I have a string "greet('eric')" is it possible to convert it 开发者_JAVA百科to a function call passing "eric" as argument?
eval() is your friend ! http://www.w3schools.com/jsref/jsref_eval.asp
You, me, him her and them fWord('ing') hate eval. There's always another way.
callMethod = function(def) {
//all the variables are function references
var approvedMethods = {greet: greet, love: love, marry: marry, murder: murder, suicide: suicide},
split = def.split(/\(/); //split[0] contains function name, split[1] contains (unsplit) parameters
//replace last ) and all possible string detonators left-over
split[1] = split[1].replace(/\)$/, '').replace(/[\'\"]/g, '').split(','); //contains list of params
if (!approvedMethods[split[0]])
return 'No such function.';
approvedMethods[split[0]].apply(window, split[1]);
}
//Called like this:
callMethod("greet('eric')");
Replace window reference with whatever.
I'm not sure I've understood your question correctly, but are you looking for the eval() function?
eval("greet('eric')");
It is as easy as typing
eval("greet('eric')");
without eval
var greet = function (name) {
console.log("Hi " + name);
},
greetstr = 'greet("Eric")';
var greeter = greetstr.split('("');
window[greeter[0]]( greeter[1].replace(/\)|"/g,'') );
Bottom line 1: use eval with care
Bottom line 2: avoid constructions like this.
Just to be sure you have all possibilities @ your disposal: setTimeout(greetstr,0);
Mmmm, there is an eval
in there somewhere ;)
精彩评论