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

Difference analysis between eval and window.eval_javascript skills

WBOY
Release: 2016-05-16 18:09:08
Original
1152 people have browsed it
Is there any difference between them?

During the development process, few people seem to add an extra window, which is considered unnecessary. For example, the callback function in the Ajax process parses the JSON format string
Copy code The code is as follows:

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

Usually used directly eval, not var json = window.eval('(' str ')');
For example, alert is used when debugging, and few people use window.alert; event is used to obtain event objects in IE, and few people use it. window.event. (Firefox also supports event but not window.event in some cases. Interested students can read this article to get the event object)

However, due to differences in the implementation of each engine, there are still differences between them. of.
Copy code The code is as follows:

var x = 5;
function fn() {
var x = 'jack';
eval('x=10;');
}
fn();
alert(x); // -->5

The output in all browsers is 5, which means that after calling fn, eval modifies the local variable x in fn, not the global x. That is, the closure environment executed by eval is within fn.

Modify and replace eval in the above code with window.eval. After testing, we found that the performance in each browser is different.

IE6/7/8: Still outputs 5, that is, the global variable x is not modified, but the local variable x is still modified.
IE9/Firefox/Safari/Chrome/Opera: Output 10, the global variable x is modified.

We can draw the conclusion
In IE6/7/8, eval is the same as window.eval. It is a local closure when written in a custom function, otherwise it is a global closure.
In IE9/Firefox/Safari/Chrome/Opera, eval is the same as IE6/7/8 above. Even if window.eval is written in a custom function, it is a global closure.

Also: window.execScript in IE is always executed under a global closure, and surprisingly Chrome also supports this method. Oh, Chrome policy is a standard, and IE cannot be missing one.
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