Home > Web Front-end > JS Tutorial > body text

IE Handling when eval encounters function_javascript skills

WBOY
Release: 2016-05-16 18:03:29
Original
1237 people have browsed it

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!