为什么未定义的var不被添加到窗口对象JavaScript

Why undefined var is not added to window object JavaScript?

本文关键字:窗口 对象 JavaScript 添加 未定义 var 为什么      更新时间:2023-09-26

据我所知,以下声明不会为变量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
}

现在如果我想使用访问变量aabb,我只能访问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中的局部变量。