1

几天前,我问了一个关于在外部脚本执行过程中动态修改函数代码的问题,我被告知完全忘记这个概念。我不确定我明白为什么会这样。让我举个例子:

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

我意识到这是一个相当微不足道的例子,但肯定有一些用途可以从能够动态修改函数中派生出来,这本身就非常有用。

4

4 回答 4

8

尽管这可能会满足您的需求,但从现在起 6 个月后,您(或维护您的代码的人)将会“WTF?!”

如果您的用例是根据某些条件发出警报或写入,为什么不编写两个不同的函数呢?或者让您的函数采用另一个决定输出模式的参数。或者传入一个函数作为执行实际输出的参数。有些东西,你知道,在理智的一面多一点。;-)

于 2009-01-28T07:08:19.070 回答
5

在某些情况下,改变函数的行为可能很有用,但有更好的方法来做到这一点。在您的示例中,您可以通过将函数作为参数传递(类似于策略模式)来创建以不同方式处理输出的函数的新实例:

function makeDisplay(displayStrategy) {
    return function(msg) {
        // I'm assuming you would do some additional processing here...

        displayStrategy(msg);
    }
}

var display = makeDisplay(alert);

// now modify display to use document.write
display = makeDisplay(function(msg) { document.write(msg); });
于 2009-01-28T07:05:54.800 回答
0

好吧,使用eval可能是一个安全问题,但实时修改功能是可以的。无论如何,你还能怎么做记忆?

虽然想一想,改变方法签名不是一个好主意,但其他人不会知道如何调用这个函数,因为它取决于执行顺序,通常不容易跟踪。

于 2009-01-28T06:58:20.073 回答
0

我发现自己需要在没有特定供应商 javascript 的源代码的情况下执行此操作;所以这可能是一个合法的用例。我同意,如果您有其他选择,最好以更有条理的方式进行,将原始功能编辑为更灵活。

于 2014-02-05T14:24:11.050 回答