Case 1: If there is no function in eval, directly execute:
Eval ("alert ('ss');"); // all browsers output correctly
Case 2: A function exists in eval and the function is executed immediately:
Eval ("(function () {alert ('ss') ;}) ();"); // all browsers correctly output
Case 3: There is a function in eval. Use the variable to save the function reference and call the function:
Var f = eval ("(function () {alert ('ss ');})");
F (); // error in IE: the object is missing and other browsers are normal
When eval defines a function and returns it to a variable, IE reports the following error: the object is missing. It can be seen that the function defined in eval in IE cannot be successfully returned to the eval external.
Solution: Make the function object return as an execution result:
Method 1:
Var f = eval ("(function () {return function () {alert ('ss ');}})()");
F (); // correct output by all browsers
Call an immediate function in eval. After the function is executed, a function object is returned. At this time, the reference of the function object is successfully returned to the external variable.
Method 2:
Var f = eval ("(false | function () {alert ('ss ');})");
F (); // all browsers are successfully output
This method is also used in jquery. function is returned as the execution result of or expression, and the problem can be solved successfully. Of course, the expression is not limited to the above false | function () {}. All expressions can solve the problem if function is successfully returned:
/* And expression :*/
Var f = eval ("(true & function () {alert ('ss ');})");
F (); // all browsers output normally
/* Ternary expression :*/
Var f = eval ("(true? Function () {alert ('ss ');}:'');");
F (); // all browsers output normally