Javascript 将全局变量分配给自己

标签 javascript

谁能解释一下(全局范围内的代码)

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 时,就根本没有声明变量/函数。因此引用错误。

一些例子。

函数语句:

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

关于Javascript 将全局变量分配给自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4409897/

相关文章:

javascript - 加载所有元素后更新背景

javascript - 如果选择取消,FB.login 不会调用回调

javascript - 我需要angularjs中没有数组括号的输出值

javascript - 将 JavaScript 字符串传递给编译为 WebAssembly 的 Rust 函数

javascript - 如何在表单中发布ajax响应

javascript - AngularJS - 从 json 文件加载其 src 时 iframe 不显示

javascript - Accordion 条件打开和关闭功能

javascript - 表单验证(包括输入文件)的问题

Javascript 代码不会交叉淡入淡出

javascript - node的微服务架构会不会降低效率,增加响应时间?有什么解决办法还是我的理解有误?