问题描述
几天前,我问了一个有关在外部脚本执行过程中动态修改函数代码的问题,并被告知要完全忘记这个想法。我不确定我为什么会这样。让我举一个例子:
A few days ago, I asked a question regarding dynamically modifying a function's code midway through the outerlying script's execution and I was told to completely forget ever coming upon the notion. I'm not sure I understand why that is. Let me give an example:
<script>
var display = function(msg)
{
alert(msg);
}
// Now, at the moment, the display() function
// is receiving a single parameter and alerting
// it to the user. I'm now going to use eval()
// to modify the display() function.
eval('display = ' + display.toString().replace('alert(', 'document.write('));
// Now, the display() function writes its parameter
// to the document as opposed to alerting it.
</script>
我意识到这是一个相当琐碎的示例,但是肯定可以通过动态修改函数来获得某些用途,而这本身就非常有用。
I realize this is a rather trivial example, but there must surely be some use that can be derived from being able to dynamically modify a function, something so useful by itself.
推荐答案
尽管这可能会完成您需要做的事情,但是从现在开始的6个月后,您(或维护您代码的人)将开始 WTF? !
Although this may do what you need it to do, 6 months from now you (or the person maintaining your code) will be going "WTF?!"
如果您的用例是基于某种情况来发出警报或编写,为什么不编写两个不同的函数呢?或者让您的函数采用另一个参数来决定输出模式;或者传递函数作为执行实际输出的参数;在理智的一面,还有一些小。;-)
If your use case is to alert or write based on some condition, why don't you write two different functions? Or have your function take another parameter that decides the output mode. Or pass in a function as a parameter that performs the actual output. Something, you know, a little more on the sane side. ;-)
这篇关于为什么在中间执行时动态修改JavaScript函数的代码是一件坏事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!