About the difference between Window.eval and eval

Source: Internet
Author: User
Tags closure eval json

In the development process, it seems that very few people go to add an extra window, feel superfluous. Like the Ajax process, the callback function parses the JSON format string
Copy code code as follows:
...

function Callback (str) {
var json = eval (' (' + str + ') ');
}
...

Eval is usually used directly, not var json = window.eval (' + str + ');
For example, when debugging using alert, few people use Window.alert;ie to get event objects using events, and few people use window.event. (Firefox also supports event in some cases and does not support window.event.) Interested students look at this article to get the event object of the whole family)

However, because of the different engine implementation differences, they are still the difference.
Copy code code as follows:

var x = 5;
function fn () {
var x = ' Jack ';
Eval (' x=10; ');
}
FN ();
alert (x); -->5

All browsers output 5, which means that eval modifies the local variable x within FN, not the global X, after invoking FN. That is, the closure environment in which the eval executes is within FN.

Modified, the above code to change the eval to Window.eval, after testing found that the performance of different browsers are different.

IE6/7/8: Still output 5, that is, the global variable x is not modified, the modified is still local variable x.
Ie9/firefox/safari/chrome/opera: Output 10, modified by global variable X.

We can draw a conclusion.
In Ie6/7/8, like Eval and Window.eval, writing in a custom function is a local closure, otherwise a global closure.
In Ie9/firefox/safari/chrome/opera, the eval and above Ie6/7/8,window.eval are also global closures even if written in a custom function.

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.