繁体   English   中英

Javascript为自己分配全局变量

[英]Javascript assigning global variables to themself

任何人都可以解释一下(全局范围内的代码)

var a = a || 4 // a exists & is 4
window.a = window.a || 4 // a exists & is 4
window.a = a || 4 // a is undefined error
a = a || 4 // a is undefined error

解释这4个作业之间的区别以及为什么有些作业正确处理而其他作业却不正确。

[编辑]此特定示例在V8 Chrome控制台上进行了测试。

var a = a || 4 // var a is evaluated at compile time, so a is undefined here
window.a = window.a || 4 // window.a is simply undefined
window.a = a || 4 // no var a, therefore the variable doesn't exist, = reference error
a = a || 4 // again, no var, reference error

var语句在最接近的封装范围内声明变量/函数,并将其设置为undefined 当没有var ,根本没有声明任何变量/函数。 因此参考错误。

一些例子。

function说明:

foo(); // works
function foo() {}

bar(); // TypeError: undefined is not a function
var bar = function(){};

var陈述式:

function test(foo) {        
    if (foo) {
        var bar = 0; // defined at compile time in the scope of function test
    } else {
        bar = 4; // sets the bar above, not the global bar
    }
    return bar;
}

console.log(test(false)); // 4
console.log(bar); // ReferenceError

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM