这是我在学习 JavaScript 作用域时发现的一些有趣的东西。
代码
var foo = "This is a global variable.";
var bar = function() {
alert(foo);
foo = "Value has been modified";
}
bar();
alert(foo);
这给出了您认为会得到的正常响应,但如果我更改这一行:
来自:
foo = "Value has been modified";
到:
var foo = "Value has been modified";
我得到的 foo 值为 undefined,这是为什么?既然函数是全局范围的,为什么它不接受前面的 var 关键字呢?
编辑
现在我基本上明白发生了什么,函数栏中的 var foo
将变得最重要 因为 var 关键字 并被提升,但它会被提升没有值它已分配。
最佳答案
在 var
语句中,有两部分 - 实际声明:
var foo //;
...和可选的赋值:
= 1234567890;
如果没有对其进行赋值,则变量(如果尚未定义)默认为 undefined
。
变量声明部分被移动到当前范围的顶部(函数的开始),但不是实际赋值(所以它等同于以下):
var foo = "This is a global variable.";
var bar = function() {
var foo; // undefined
alert(foo); // yes, it's undefined
foo = "Value has been modified"; // modify local, not global
}
bar();
alert(foo); // the global one
函数创建自己的作用域——例如:
var test = function ()
{ var bar = 1;
console.log(bar); // 1
};
test();
console.log(bar); // ReferenceError: bar is not defined
关于javascript - 变量 : local scope, 全局范围还是 JavaScript 引擎?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19625732/