在 JavaScript 中,未声明的变量赋值可以在函数范围之外访问

Undeclared assignment of variables are accessed outside of the function scope in JavaScript?

本文关键字:函数 范围 访问 赋值 JavaScript 未声明 变量      更新时间:2023-09-26

通常,在函数内声明的变量(变量声明)只能由该函数及其内部函数访问。但是,函数内变量的未声明赋值可以通过使其成为全局变量来访问 JavaScript 中的函数 Scope 之外。为什么会这样?

var hello = function() {
   number = 45;
};
hello();
console.log(number);    // 45 is printed in the console

因为规范是这样说的。

"use strict";添加到文件或函数的顶部以禁止此操作。

出现在var声明中的变量赋值被视为全局变量(全局上下文的属性)赋值。在"严格"模式下,此类分配会引发错误。

这就是

JavaScript的工作方式。如果正确声明number,则全局不可见:

var hello = function() {
   var number = 45;
}
hello();
console.log(number);    // undefined is printed in the console