0

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 to a function call passing "eric" as argument?

ajsie
  • 77,632
  • 106
  • 276
  • 381

5 Answers5

2

eval() is your friend ! http://www.w3schools.com/jsref/jsref_eval.asp

Elian
  • 323
  • 1
  • 7
  • 2
    Oh totally forgot eval(). Isn't it the other way around, its evil? – ajsie Apr 20 '11 at 06:12
  • @weng Eval is only evil if you misuse it – Peter Olson Apr 20 '11 at 06:15
  • 2
    The call of a thousand screaming virgins tearing at their flesh accompany your answer. – Zirak Apr 20 '11 at 06:15
  • W3Schools bashing seems to be fashionable nowadays. They may be wrong in many aspects, but in their days (w3schools started in 1999) they were a great source of information to many. Maybe they'll catch up someday. – KooiInc Apr 22 '11 at 08:00
2

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.

Zirak
  • 38,920
  • 13
  • 81
  • 92
1

I'm not sure I've understood your question correctly, but are you looking for the eval() function?

eval("greet('eric')");
Anders Lindahl
  • 41,582
  • 9
  • 89
  • 93
1

It is as easy as typing

eval("greet('eric')");
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
1

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 ;)

KooiInc
  • 119,216
  • 31
  • 141
  • 177