【问题标题】:Why undefined var is not added to window object JavaScript?为什么未将 undefined var 添加到窗口对象 JavaScript?
【发布时间】:2013-06-10 17:51:13
【问题描述】:

据我所知,以下声明不会向变量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,因为在声明中我没有为它分配任何值并且它仍然是未定义的?

谢谢。

【问题讨论】:

  • 您已将 aa 重新定义为在函数范围内,并且由于您没有分配值,因此它已分配 undefined
  • 您正在函数中重新声明变量 aa
  • @JonathandeM.:你的意思是undefined 是分配给变量的值吗?

标签: javascript scope global-variables undefined window-object


【解决方案1】:

看看我的cmets

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

更多信息请阅读此great Ebook

【讨论】:

  • 那么您的意思是undefined 是在我的情况下分配给变量的值吗?
  • 是的,默认值是undefined,除非你手动赋值,var a = undefined等于var b;a === b
  • 感谢您消除我的误解。我一直认为var anothing is there。但现在我能理解的是there may occur a variable 'a' which is inside this scope but no value has been assigned to it。如果我错了,请纠正我。
  • undefined 是一个特殊值,表示没有定义任何内容。所以不定义或定义 undefined 是一样的。关于这里的范围a good ebook
【解决方案2】:

尝试从您的函数中删除var aa;

这里发生的是function scope。您已将aa 声明为function a 中的局部变量。局部变量被设置为 11。

【讨论】:

    猜你喜欢
    • 2021-08-18
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多