The Dangers of Eval()

Efficient JavaScript code - UserJS.org

Quote:

eval is evil


The 'eval' method, and related constructs such as 'new Function', are extremely wasteful. They effectively require the browser to create an entirely new scripting environment (just like creating a new web page), import all variables from the current scope, execute the script, collect the garbage, and export the variables back into the original environment. Additionally, the code cannot be cached for optimisation purposes. eval and its relatives should be avoided if at all possible.


Timers take too much time


Because a timer normally has to evaluate the given code in the same way as eval, it is best to have as little code as possible inside the evaluated statement. Instead of writing all of the code inside the timeout statement, put it in a separate function, and call the function from the timeout statement.


Here's some code that Lectora output:


[php]function text718actionShow() {

setTimeout("if(!text718.isVisible()) { setTimeout( 'text718.objLyr.doTrans( 0, 29, 1, null, text718.objLyr.x, text718.objLyr.y, -489, -43, winW+66, winH+296, 0 )', 22000 ); }", 1 )

}[/php]


Jesus christ, it's got a setTimeout inside a setTimeout! Both of them performing evals! Not only that, but the outer timeout delays code execution by one millisecond making it entirely pointless!


Who's responsible for this steaming pile?


Also:


[php]function action6280(fn){

trivExitPage('a001_main_nav_glossary.html',true);

if(fn) eval(fn);

}


function action6281(fn){

VarglossarySwitch.set('monocytes');

if(fn) eval(fn);

}


function action6272(fn){

trivExitPage('a001_main_nav_glossary.html',true);

if(fn) eval(fn);

}


function action6273(fn){

VarglossarySwitch.set('erythrocytes');

if(fn) eval(fn);

}[/php]


Look at all that eval (ignoring the fact that every single one of those actions--on every one of 147 pages--is called passing no parameters, thus invalidating the entire need for the if(fn) block).

Discussions have been disabled for this post