代码之家  ›  专栏  ›  技术社区  ›  Hexagon Theory

为什么在执行过程中动态修改JavaScript函数的代码是件坏事?

  •  1
  • Hexagon Theory  · 技术社区  · 16 年前

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

    <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 回复  |  直到 16 年前
        1
  •  8
  •   davogones    16 年前

    尽管这可以做你需要做的事情,但6个月后你(或维护你的代码的人)将成为“WTF”?!"

    如果您的用例是基于某种条件发出警告或编写,为什么不编写两个不同的函数呢?或者让函数接受另一个决定输出模式的参数。或者将函数作为执行实际输出的参数传入。一些东西,你知道,一个 更理智的一面。;-)

        2
  •  5
  •   Matthew Crumley    16 年前

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

    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); });
    
        3
  •  0
  •   vava    16 年前

    eval 可能是安全问题,但可以实时修改函数。你还能怎么做回忆录呢?

    尽管,想想看,更改方法签名并不是一个好主意,但是其他人在这之后不会知道如何调用这个函数,因为它取决于执行顺序,而且通常不容易跟踪。

        4
  •  0
  •   Jeremy Warne    11 年前

    我发现自己需要在没有特定供应商javascript的源代码的情况下这样做;因此这可能是一个合法的用例。我同意,如果你有另一个选择,最好以更有组织的方式来做,编辑原来的功能更灵活。