Can Javascript get a function as text? I'm thinking like the inverse of eval().
function derp() { a(); b(); c(); }
alert(derp.asString());
The result would be something like
"a(); b(); c();"
Does it exist?
Can Javascript get a function as text? I'm thinking like the inverse of eval().
function derp() { a(); b(); c(); }
alert(derp.asString());
The result would be something like
"a(); b(); c();"
Does it exist?
Updated to include caveats in the comments below from CMS, Tim Down, MooGoo:
The closest thing available to what you're after is calling .toString() on a function to get the full function text, like this:
function derp() { a(); b(); c(); }
alert(derp.toString()); //"function derp() { a(); b(); c(); }"
You can give it a try here, some caveats to be aware of though:
.toString() on function is implementation-dependent (Spec here section 15.3.4.2)
(function() { x=5; 1+2+3; }).toString() == function() { x=5; }object.toString() method, in the case of functions you get the full function text :)name is non-standard and isn't supported in all browsers. Notable non-supporters include (would you believe) IE.Function.prototype.toString method returns an "implementation-dependent representation of the function", and in some implementations (Opera Mobile and Older Safari versions IIRC) it will not return the source code of the function, also the name property on function objects is non-standard.FunctionExpression, like (function() {}).toString() returns a string that does not represent the grammar of a FunctionDeclaration: "function () {}", the mandatory Identifier token is missing... BTW I've found the issues where Opera Mobile made PrototypeJS and jQuery fail.