36

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?

1

2 Answers 2

50

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:

  • The .toString() on function is implementation-dependent (Spec here section 15.3.4.2)
    • From the spec: An implementation-dependent representation of the function is returned. This representation has the syntax of a FunctionDeclaration. Note in particular that the use and placement of white space, line terminators, and semicolons within the representation string is implementation-dependent.
    • Noted differences in Opera Mobile, early Safari, neither displaying source like my example above.
  • Firefox returns a compiled function, after optimization, for example:
    • (function() { x=5; 1+2+3; }).toString() == function() { x=5; }
Sign up to request clarification or add additional context in comments.

12 Comments

@delnan - Various objects override the object.toString() method, in the case of functions you get the full function text :)
I knew js was very dynamic, reflective, has first-class functions, etc. But this is... well, I don't know if it's awesome or unnecessary bling-bling. A mix of both, I guess.
name is non-standard and isn't supported in all browsers. Notable non-supporters include (would you believe) IE.
@Nick, This will work on almost all browsers, but maybe is worth mentioning that the 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.
@Nick, yes but I think the specification should be more formal, in almost all implementations, the spec. then is not strictly followed, for example, an anonymous 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.
|
10
function derp() { a(); b(); c(); }

alert(derp.toString());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.