IE: When eval encounters function processing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.