Accessing Global Vars with Window

2019-05-11 06:15发布

问题:

Why doesn't window.x print out 10?

eval("var x = 10;");
console.log(window.x); // undefined
console.log(x); // 10

http://jsfiddle.net/kzd4z/1/

回答1:

You have selected onLoad in the side panel, which wraps everything in an anonymous function. If you pick "No wrap" it works.

Demo: http://jsfiddle.net/kzd4z/2/

You can see this by viewing source:

//<![CDATA[ 
window.onload=function(){
eval("var x = 10;");
console.log(window.x); // undefined
console.log(x); // 10
}//]]>  


回答2:

Expanding on @Dennis' answer, because using "No Wrap" wraps your entire function within an anonymous function, x is now part of the local scope of that anonymous function. Like any function in javascript, using the keyword var creates this local variable... You can remove the "No Wrap" option on jsfiddle, or just drop the var keyword (creating a variable in the global scope).

eval("x = 10;");
console.log(window.x); // 10
console.log(x); // 10

DEMO

Correct me if I'm wrong, but this looks like what is happening to me...