javascript - 为什么在函数内部定义的 x 会成为全局变量,而我一开始就没有将其声明为变量?

标签 javascript

预先非常感谢您对我的帮助!

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/

相关文章:

php - 如何将 PHP 变量传递给 Javascript?

javascript - 我怎样才能让这个数字输入接受逗号?

javascript - 在 Ajax 中拉取更新...我可以只是一个可观察者吗?

javascript - 使播放按钮一次显示在悬停 1 个图像上

javascript - 从 D3 line() 获取点数组

JavaScript生成的Materialise卡片显示问题

javascript - 元素类型无效 : expected a string (for built-in components) or a class/function (for composite components) but got: undefined React

javascript - Puppeteer 在当前窗口而不是新窗口中启动一个新选项卡

javascript - 如何获取具有某个类属性的所有 HTML 元素?

javascript - 如何在保存到数据库之前散列密码以与 Passport 模块(本地 Passport )兼容