Accessing Global Vars with Window

帅比萌擦擦* 提交于 2019-12-10 10:26:18

问题


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...



来源:https://stackoverflow.com/questions/20818236/accessing-global-vars-with-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!