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
  • 74,062
  • 99
  • 267
  • 376

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
  • 37,288
  • 12
  • 78
  • 90
1

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

eval("greet('eric')");
Anders Lindahl
  • 39,992
  • 8
  • 84
  • 90
1

It is as easy as typing

eval("greet('eric')");
Peter Olson
  • 131,160
  • 48
  • 197
  • 239
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
  • 112,400
  • 31
  • 139
  • 174