Javascript可以获得文本的功能吗? [英] Can Javascript get a function as text?
本文介绍了Javascript可以获得文本的功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想像eval()的逆函数。
函数derp(){a(); B(); C(); }
alert(derp.asString());
结果会像a(); b(); c(); / p>
是否存在?
解决方案
请从 CMS 的以下评论中, Tim Down , MooGoo :
最接近您的内容的是调用 .toString()
以获得完整功能文本,如下所示:
function derp(){a(); B(); C(); }
alert(derp.toString()); //function derp(){a(); b(); c();}
你可以在这里试试,但需要注意的一些注意事项:
-
.toString()
on函数是实现相关的( 在此处参考部分 15.3.4.2 )
- 函数的依赖表示被返回。该表示具有 FunctionDeclaration 的语法。特别要注意的是,在表示字符串中使用和放置空格,行结束符和分号是依赖于实现的。
- Opera Mobile,Early Safari中的注意区别,既不显示源代码我的例子如上。
- Firefox在优化后返回一个编译函数,例如:
-
(function(){x = 5; 1 + 2 + 3;})。toString() ==
function (){x = 5; }
-
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:
- 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; }
这篇关于Javascript可以获得文本的功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文