Case 1: There is no function in eval, execute it directly:
eval("alert('ss');");//All browsers correctly output
Case 2: There is a function in eval, and the function is executed immediately:
eval("(function(){alert('ss');})();");//All browsers output correctly
Case 3: There is a function in eval, use a variable to save the function reference and Call this function:
var f=eval("(function(){alert('ss');})");
f();//Error reported under IE: Missing object, other browsers are normal
When defining a function in eval and returning it to a variable, IE reports an error: Missing object. It can be seen that the function defined in eval under IE cannot be successfully returned to outside eval.
Solution: Return the function object as an execution result:
Method 1:
var f=eval("(function(){ return function(){alert ('ss');}})()");
f();//All browsers correctly output
eval to call a function that is executed immediately. After the function is executed, it returns a function object. This When 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 successfully output
. This method is also used in jquery. The function is returned as the execution result of the or expression, which can also successfully solve the problem. Of course, expressions are not limited to the above false||function(){}. Various expressions can solve the problem as long as they can successfully return function:
/* and expressions: */
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