function.toString()有哪些实际用途? [英] What are some real world uses for function.toString()?

查看:550
本文介绍了function.toString()有哪些实际用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中注意到,如果你定义一个函数,比如说 myfunction(),然后调用 myfunction.toString(),您将获得该函数的源文本。是否有任何有趣/现实世界的使用?

I've noticed in JavaScript that if you define a function, say myfunction(), and then call myfunction.toString(), you get the text of the source for that function. Are there any interesting/real world uses of this?

推荐答案

好吧,你可以用它轻松重新定义一个函数:

Well, you can use it to easily redefine a function:

function x() { alert('asdf'); }
eval(x.toString().replace('asdf','hello'));
x();

这将提醒字符串hello而不是字符串asdf。

This will alert the string "hello" instead of the string "asdf".

这可能很有用。另一方面,由于难以维护代码,自修改代码常常不受欢迎......

This may be useful. On the other hand, self modifying code is often frowned upon because of the difficulty to maintain it...

这篇关于function.toString()有哪些实际用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆