Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How override eval function in javascript?

For example:

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

But this code is not working.

like image 392
ko1ik Avatar asked Apr 02 '10 13:04

ko1ik


People also ask

What is the alternative for eval function in JavaScript?

An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().

How do I override JavaScript?

You can override any built-in function by just re-declaring it. parseFloat = function(a){ alert(a) }; Now parseFloat(3) will alert 3.

Is function overriding possible in JavaScript?

It is true that JavaScript supports overriding, not overloading. When you define multiple functions that have the same name, the last one defined will override all the previously defined ones and every time when you invoke a function, the last defined one will get executed.

Why we should not use eval in JavaScript?

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.


1 Answers

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

like image 53
bobince Avatar answered Oct 12 '22 00:10

bobince