[[scope]] 键中的块是什么,它是什么时候创建的?

What is block inside [[scope]] key and when it is created?

我尝试了以下代码

let let_arr = [];
for (let i = 0; i < 4; i++) {
  let_arr[i] = () => {
    return {
        let_i: i
    }
  };
}
console.log(let_arr);

当我们使用 let in for 循环时,我发现块键存在。

[ƒ, ƒ, ƒ, ƒ]
  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++) 缺少块元素。

[[Scopes]]: Scopes[2]
    0: Script {let_arr: Array(4), var_arr: Array(4)}
    1: Global {window: Window, self: Window, document: document, name: "", location: Location, …}

这是预期的行为,因为如果您使用 var 声明变量,则块作用域中没有变量。在这种情况下,它将被提升到全局范围。您可以阅读有关块范围的更多信息 here.

Javascript函数实际上是闭包,也就是说,当你在某个地方保存一个函数时,不仅保留了它的代码,而且还保留了创建时可用的所有变量时间。变量存储在名为 scopes 的字典中,它们可以相互嵌套(“作用域链”)。

为了节省内存,引擎只保留函数中实际使用的作用域。如果范围不包含 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