How override eval function in javascript?

前端 未结 6 1720
滥情空心
滥情空心 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:41

    Although not portable, the following approach works in some places where it otherwise wouldn't (as it satisfies ES5's requirements that A) it be retrieved as a Reference in a MemberExpression, not a Value and B) it results in the ‘standard builtin function.’ — ES5 #15.1.2)

    (function() {
      var proxied = window.eval
      with({get eval(){ console.log('eval called'); return proxied }}) {
        /* client code */
      }
    })()
    

    This obviously only applies if you can wrap the client code in a with() statement; though in many situations, that shouldn't be hard. Obviously, the same approach can shadow window with another object with all of its' properties, and a getter-proxied eval.

    Environments that don't support SpiderMonkey's get statement, may be able to use ES5's defineProperty. Look into that yourself.

提交回复
热议问题