Javascript 可以将函数作为文本获取吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3379875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can Javascript get a function as text?
提问by Brandon
Can Javascript get a function as text? I'm thinking like the inverse of eval().
Javascript 可以将函数作为文本获取吗?我在想像 eval() 的倒数。
function derp() { a(); b(); c(); }
alert(derp.asString());
The result would be something like "a(); b(); c();"
结果将类似于“a(); b(); c();”
Does it exist?
它存在吗?
回答by Nick Craver
Updated to include caveats in the comments below fromCMS, Tim Down, MooGoo:
更新以在以下来自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:
最接近您所追求的是调用.toString()一个函数来获取完整的函数文本,如下所示:
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 heresection 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; }
- 在
.toString()上功能是实现相关的(规格此部分15.3.4.2)- 来自规范:返回函数的依赖于实现的表示。此表示具有FunctionDeclaration的语法。请特别注意,表示字符串中空格、行终止符和分号的使用和放置取决于实现。
- 注意到 Opera Mobile 和早期 Safari 中的差异,它们都不像我上面的例子那样显示源代码。
- Firefox 返回一个编译后的函数,经过优化,例如:
(function() { x=5; 1+2+3; }).toString()==function() { x=5; }
回答by CD..
function derp() { a(); b(); c(); }
alert(derp.toString());

