SoFunction
Updated on 2025-03-06

IE When eval encounters function processing

Case 1: There is no function in eval, execute it directly:
eval("alert('ss');");//All browsers output correctly
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 variables to save the function reference and call the function:
var f=eval("(function(){alert('ss');})");
f();//IE error: Missing object is normal for other browsers
When a function is defined in eval and returned to a variable, IE reports an error: Missing object. It can be seen that the function defined in eval under IE cannot successfully return to the outside of eval.

Workaround: Make the function object return as an execution result:

Method 1:

var f=eval("(function(){ return function(){alert('ss');}})()");
f();//All browsers output correctly
An immediately executed function is called in eval. After the function is executed, a function object is returned. At this time, the reference to 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 a method used in jquery. Returning function as the execution result of an expression can also successfully solve the problem. Of course, expressions are not limited to the above false||function(){}. As long as various expressions can successfully return function, they can solve the problem:

/* with expression: */
var f=eval("(true&&function(){alert('ss');})");
f();//All browsers output normally

/* Tripartite expression: */
var f=eval("(true?function(){alert('ss');}:'');");
f();//All browsers output normally