变量,在 window.onload 函数的循环内定义,在 window 级别获取全局范围
Variable, defined insde for loop of window.onload function, gets global scope at window level
我有一个函数设置为 window.onload 事件。在该函数中,我有一个 for 循环 ,它在每次迭代中将变量 unit 定义为 [=32 类型的新对象=]。因此,我在 window 范围内有一个变量 unit,保存最后创建的对象!我一直认为,循环内的变量是面向循环的。我仔细检查了 unit 变量在我的代码中的任何地方都没有其他声明。我做错了什么?
Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.
— MDN.
var
将变量范围限定为函数,而不是循环。
要将变量限定为块,请使用 let
。
我有一个函数设置为 window.onload 事件。在该函数中,我有一个 for 循环 ,它在每次迭代中将变量 unit 定义为 [=32 类型的新对象=]。因此,我在 window 范围内有一个变量 unit,保存最后创建的对象!我一直认为,循环内的变量是面向循环的。我仔细检查了 unit 变量在我的代码中的任何地方都没有其他声明。我做错了什么?
Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.
— MDN.
var
将变量范围限定为函数,而不是循环。
要将变量限定为块,请使用 let
。