Javascript 可变局部和全局混淆
Javascript variable local and global confusion
这是代码。
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,它将被声明为全局变量。
因为您在 b
之前没有输入 var。它被宣布为全球性的,因此您可以在任何地方看到它的价值。
其中 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 ........[]
您没有将 b
声明为局部变量。您将其分配为用于初始化 a
的表达式的一部分。由于它没有声明为函数的局部变量,因此创建了一个全局变量。
要获得两个具有相同初始值的局部变量,请执行以下操作:
function x() {
var b = 10, a = b;
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
它具有全局作用域:)
这是代码。
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,它将被声明为全局变量。
因为您在 b
之前没有输入 var。它被宣布为全球性的,因此您可以在任何地方看到它的价值。
其中 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 ........[]
您没有将 b
声明为局部变量。您将其分配为用于初始化 a
的表达式的一部分。由于它没有声明为函数的局部变量,因此创建了一个全局变量。
要获得两个具有相同初始值的局部变量,请执行以下操作:
function x() {
var b = 10, a = b;
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
它具有全局作用域:)