views:

69

answers:

3

I am trying to evaluate a function in a new context, ie, one that contains a certain word defined that does not exist in the scope. It is easy enough if I have the definition of the function as a string, but I would like to provide the ability to do this with a regular list of functions, like so:

var funcs = {
  first: function() { return 'yayaya'; },
  second: function() { return 'okokok' + keyword; },
  ...
};

then later:

function Thing () {};

for (func in funcs) {
  var definition = funcs[func].definition();
  var keyword = "NOW I AM THE KEYWORD";
  var actual_func_with_keyword_defined = eval(definition);
  Thing.prototype[func] = actual_func_with_keyword_defined;
}

What I am missing is the definition() function or equivalent, which returns the source of the function. Is this possible in javascript?

+2  A: 

Try simply taking out the .definition().

Abraham Pinzur
You're answer worked! So I didn't actually need the text to the function after all, eval() will evaluate pure functions! Still, the other guy answered the original question, so I gave the check to him.
kaleidomedallion
Though his is probably a better answer, if it means the eval() call gets taken out =)
RMorrisey
+1  A: 

This will work, though I'm sure there's a lengthier, more elegant solution:

function foo() {
}
var bar = '' + foo; //type cast to a string by adding an empty string
alert(bar);
RMorrisey
You answered the original question, this yields the function definition. Thank you!
kaleidomedallion
On a side note, are you really sure that you need to use eval? It sounds like you might be able to get away with adding an extra parameter to the method signature, or store the keyword as a property on the object.
RMorrisey
Sure thing! Can you hit the checkmark next to it so I get points? =D
RMorrisey
In JavaScript, the standard way of "casting" an object/value to a string is to call toString() on the value. If the value can be null/undefined etc., you can use String(foo) to be safe.
Ates Goral
+2  A: 

The JS standard way is to call toString() on the function. Like so:

function myFun() {}

myFun.toString() // gives "function myFun() {}",
                 // potentially with white space differences
Ates Goral