gpt4 book ai didi

javascript - 这个函数在这个 block 上有闭包吗?

转载 作者:行者123 更新时间:2023-11-29 15:07:33 24 4
gpt4 key购买 nike

我正在尝试使用闭包,但我没有将函数包含在函数中,而是将函数包含在 block 中。由于函数不是 block 范围的,并且将被提升到 block 之外,我假设它无法访问 block 内的范围。然而,在这种情况下,该函数返回 block 范围变量。这是否意味着该函数是一个闭包?

{
let a = 'hi'
function test() {
return a
}
}
test() // hi

最佳答案

我很乐意将其称为闭包,至少根据维基百科的定义:

Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

在你的函数 test 中,变量 a 是一个自由变量,由函数使用但没有在函数内部定义。当您在 block 外调用该函数时,它会保留 a 的值。因此,您已经了解了闭包定义的要点(根据维基百科)。

当然,您问这个问题是因为它有点棘手。通常使用闭包,我们在环境中定义一个函数,然后通过将函数对象绑定(bind)到具有更广泛范围的名称来“导出”它。由于 JavaScript 处理 block 中定义的函数 声明 的方式(请参阅 Code Maniac 的 ECMAScript 规范关于处理 block 作用域函数声明的链接),您确实得到了这种效果!所以它是一种闭包,即使您从未显式导出该函数。

当然,如果你已经写了

{
let a = 'hi'
let test = () => a
}
test()

你得到一个错误。

但这行得通:

let b;
{
let a = 'hi'
let test = () => a
b = test
}
b() // "hi"

所以是的,该 block 充当可以捕获变量的非本地环境。我在想是的,可以将其称为闭包,因为它就像一个闭包(即使此行为来自 ECMAScript 2015 之前的“可选”以及对 block 内函数声明的非严格处理).如果它像鸭子一样走路,等等。

关于javascript - 这个函数在这个 block 上有闭包吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58425174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com