Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

reflection - Can Javascript get a function as text?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...