Why use eval in javascript?
|
1 answer
The method for executing arbitrary code can use variables and properties of existing objects.
var str = "if (a) { 1 + 1 } else { 2 + 2 }"; var a = true; var b = eval(str); alert("b равно : " + b); // b равно : 2 // теперь поменяем "a" a = false; b = eval(str); alert("b равно : " + b) // b равно : 4 Executing code in eval may not be safe. With this implementation, debugging is difficult.
The answer to the question is: do not need to use it.
eval :
- Requires compilation, therefore slow.
- A malicious script can find access to
evalas an argument. - Not handsome = \
- Inherits the execution context, and is associated with the area in which it is invoked.
Usage example : executing XMLHttpRequest / Ajax code. You have a server and your page, you do not want to refresh the page constantly. Send the Ajax request to the server, it returns the code, execute using eval . If you take the old example with XMLHttpRequest , then something like this:
function evalRequest(url) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { eval(xmlhttp.responseText); } } xmlhttp.open("GET", url, true); xmlhttp.send(null); } - And why is it then generally not clean up to hell? - LEQADA
- @LEQADA is sometimes very useful. For debug, for example, it is often used. - Suvitruf ♦
- oneCould the answer show an example of a case when it is really in place? - LEQADA
- @LEQADA I personally prefer not to use it. But, for example, if you need to dynamically generate code, then eval itself. - Suvitruf ♦
- @LEQADA as an example, get Ajax some JS code from the server and execute it without refreshing the page - Suvitruf ♦
|