How override eval function in javascript?

前端 未结 6 1725
滥情空心
滥情空心 2021-01-17 19:00

For example:

(function() {
      var proxied = window.eval;
      window.eval = function() {
        return proxied.apply(this, arguments);
      };
    })()         


        
6条回答
  •  轮回少年
    2021-01-17 19:47

    eval is magic. Unlike a ‘real’ function, it can read and write local variables in the caller:

    function foo() {
        var a= 1;
        eval('a+= 1');
        alert(a); // 2
    }
    

    Replace that eval with a proxied function and you've got a problem: the a+= 1 executes in the scope of the proxied function instead of foo. Depending on what's happening in the evaled code that could cause values to go missing, damage to the proxy's local, accidental globals, and so on.

    It is, therefore, impossible to replace eval with a fully-working proxy. (For simple cases which don't need the locals, you can kind of get away with it.)

提交回复
热议问题