我尝试了以下代码
let let_arr = [];
for (let i = 0; i < 4; i++) {
let_arr[i] = () => {
return {
let_i: i
}
};
}
console.log(let_arr);
当我们在 for 循环中使用 let 时,我发现 block 键存在。
[ƒ, ƒ, ƒ, ƒ]
0: () => {…}
arguments: (...)
caller: (...)
length: 0
name: ""__proto__: ƒ ()
[[FunctionLocation]]: iif.js:26
[[Scopes]]: Scopes[3]
0: Block {i: 0}
1: Script {let_arr: Array(4), var_arr: Array(4)}
2: Global {window: Window, self: Window, document: document, name: "", location: Location, …}
当使用var时
for (var i = 0; i < 4; i++)
block 元素丢失。
[[Scopes]]: Scopes[2]
0: Script {let_arr: Array(4), var_arr: Array(4)}
1: Global {window: Window, self: Window, document: document, name: "", location: Location, …}
最佳答案
Javascript函数实际上是闭包,也就是说,当你将函数保存在某个地方时,不仅保留了它的代码,而且还保留了创建时可用的所有变量。变量存储在名为范围的字典中,这些字典可以相互嵌套(“范围链”)。
为了节省内存,引擎仅保留函数中实际使用的作用域。如果作用域不包含 let/const
,则视为未使用并省略。如果作用域确实包含 let
,但该变量未在函数中使用,它也会被省略。否则,范围将被保留并附加到闭包。
一些插图:
var f
{
var a
f = () => a // Global
}
console.dir(f)
//
{
let a
f = () => a
}
console.dir(f) // Block a + Global
//
{
let a
{
let b
{
let c
f = () => b
}
}
}
console.dir(f) // Block b + Global
//
{
let a
{
let b
{
let c
f = () => eval("b")
}
}
}
console.dir(f) // 'eval' retains everything
关于javascript - [[scope]] 键内的 block 是什么以及何时创建的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68206630/