Is there a way in javascript to obtain the definition of a given function as a string, to be possibly modified and evaled?

StackOverflow https://stackoverflow.com/questions/1430761

  •  07-07-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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

OTHER TIPS

Try simply taking out the .definition().

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top