Accessing Global Vars with Window

扶醉桌前 提交于 2019-12-06 04:22:47

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
}//]]>  
brbcoding

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

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