通过窗口访问全局变量 [英] Accessing Global Vars with Window

查看:73
本文介绍了通过窗口访问全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么window.x不打印出10?

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

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

推荐答案

您已经在侧面板中选择了onLoad,该面板将所有内容包装在一个匿名函数中.如果选择不自动换行",则可以.

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

演示: 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
}//]]>  

这篇关于通过窗口访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆