为什么未定义的var不被添加到窗口对象JavaScript
Why undefined var is not added to window object JavaScript?
据我所知,以下声明不会为变量aa
添加任何值:
var aa = undefined;
function a () {
var aa;
console.log(aa); // here aa is still undefined
if(!aa) {
aa = 11; // should add to the globle scope (window Object)
bb = 12; // should add to the globle scope (window Object)
}
console.log(aa);
console.log(aa); // should be 11
console.log(bb); // should be 12
}
现在如果我想使用访问变量aa
和bb
,我只能访问bb
而不能访问aa
。我的问题是为什么aa
不能从外部访问,因为在声明中我没有分配任何值给它,它仍然是未定义的?
谢谢。
看我的注释
var aa = undefined; // global scope
function a () {
if(true) { // useless
var aa; // declare aa in the function scope and assign undefined
// to work on the global aa you would remove the above line
console.log(aa); // here aa is still undefined
if(!aa) {
aa = 11; // reassign the local aa to 11
bb = 12; // assign 12 to the global var bb
}
console.log(aa); // aa is 11
}
console.log(aa); // still in the function scope so it output 11
console.log(bb); // should be 12
}
console.log(aa) // undefined nothing has change for the global aa
更多信息请阅读这本伟大的电子书
尝试从函数中删除var aa;
。
这里发生的是函数作用域。您已经将aa
声明为function a
中的局部变量。
相关文章:
- 如何在选项卡上定义属性'的主窗口对象
- 可以从Chrome扩展修改窗口对象吗
- 在Backbone.js中为窗口对象指定变量
- 从html锚元素传递窗口对象
- 如何在ReactJS中使用窗口对象
- 在加载时调用时,窗口对象的某些变量丢失
- 清除 Javascript 中窗口对象中的自定义变量
- 窗口对象属性返回一个dom节点
- 使用窗口对象练习我的对象文字函数
- 如何从Chrome扩展访问所有窗口对象
- Jasmine在全局窗口对象上创建本地JS函数的Spy
- 如何使用Chrome'查看窗口对象中定义了哪些变量;的开发工具
- 有没有一种方法可以强制浏览器's窗口对象以重新评估鼠标所在的位置
- Safari 在尝试使用 Javascript try/catch 访问父窗口对象时未捕获异常
- 测试使用 jQuery 和窗口对象的 React 组件
- 迭代窗口对象时出现“'window.webkitStorageInfo' is deprecated”警
- 窗口对象通过对象类型测试,但 hasOwnProperty 导致错误
- node.js是否等同于浏览器中的窗口对象
- 页面工作线程 - destroy() 似乎没有删除窗口对象
- 全局变量只是“窗口”对象的属性吗?