预先非常感谢您对我的帮助!
var f2 = function() {
x = "inside f2";
};
f2();
console.log(x);
// → inside f2
当我没有使用“var x;”将 x 声明为全局变量时,为什么我将 x 作为值为“inside f2”的全局变量?在定义函数之前?
var f2 = function() {
var x = "inside f2";
};
f2();
console.log(x);
// → Uncaught ReferenceError: x is not defined
我是否正确地假设在这种情况下 x 没有定义,因为函数 f2 中没有全局变量 x,只有局部变量 x?
最佳答案
Why do I get the x as a global variable with value "inside f2" when I didn't declare it to be a global variable with "var x;" before defining the function?
因为specification says so 。如果分配给未声明的变量,则会创建全局变量。在 strict mode这会抛出一个错误(这更合理)。
Am I right in assuming that x is not defined in this case because there is no global variable x, only the local variable x within the function f2?
是的。
8.7.2
PutValue (V, W)
[...]
3. If IsUnresolvableReference(V), then
a. If IsStrictReference(V) is true, then
i. Throw ReferenceError exception.
b. Call the [[Put]] internal method of the global object, passing GetReferencedName(V) for the property name, W for the value, and false for the Throw flag.
关于javascript - 为什么在函数内部定义的 x 会成为全局变量,而我一开始就没有将其声明为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25197480/