这是代码。
function x() {
var a = b = 10;
console.log("In function a:" + a);
console.log("In function b:" + b);
}
x();
console.log("Outside function b:" + b);
console.log("Outside function a:" + a);
我预期的结果是,b
将在函数外部未定义,但事实并非如此,它的打印 b
值甚至在函数外部虽然 a
未按预期定义。
如果您不在变量声明之前放置 var,它将被声明为全局变量。
因为你没有把 var 放在 b
之前。它被宣布为全局性的,因此您可以在任何地方看到它的值(value)。
a
有 var 和 scoped。
Docs同样的
Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed. The differences between declared and undeclared variables are ........[]