javascript get function body

IF(!!!) you can get the toString(), then you can simply take the substring from the first indexOf("{") to the lastIndexOf("}"). So, something like this "works" (as seen on ideone.com):

var test = function () {alert(1);}

var entire = test.toString(); // this part may fail!
var body = entire.substring(entire.indexOf("{") + 1, entire.lastIndexOf("}"));

print(body); // "alert(1);"

2015 update

Upon revisiting the state of function decompilation, it can said that it's generally safe in certain well-considered use cases and enviroments (e.g: Node.js workers with user defined functions).

It should be put in the same bucket as eval, which is a powerful tool that has its place, but should only be used on rare occasions. Think twice, that's my only advice.

The conclusions from Kangax's new research:

  • It's still not standard
  • User-defined functions are generally looking sane
  • There are oddball engines (especially when it comes to source code placement, whitespaces, comments, dead code)
  • There might be future oddball engines (particularly mobile or unusual devices with conservative memory/power consumption)
  • Bound functions don't show their original source (but do preserve identifier... sometimes)
  • You could run into non-standard extensions (like Mozilla's expression closures)
  • ES6 is coming, and functions can now look very different than they used to
  • Minifiers/preprocessors are not your friend

"function decompilation" — a process of getting string representation of a Function object.

Function decompilation is generally recommended against, as it is a non-standard part of the language, and as a result, leads to code being non-interoperable and potentially error-prone.

@kangax on comp.lang.javascript