gpt4 book ai didi

javascript - MDN 上 JavaScript 闭包的定义是不是错了?

转载 作者:行者123 更新时间:2023-11-29 16:36:47 25 4
gpt4 key购买 nike

我已阅读 another question在 stackoverflow 上,他说:

  • A closure is one way of supporting first-class functions; it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result.
  • Or, a closure is a stack frame which is allocated when a function starts its execution, and not freed after the function returns (as if a 'stack frame' were allocated on the heap rather than the stack!).

但我也读过MDN ,它说:

A closure is the combination of a function and the lexical environment within which that function was declared.

我认为它们完全不同。但是如果 MDN 是正确的,

var a=1;
function printA(){
console.log(a);
}

这段代码包含一个函数printA()和它的词法环境(变量a),是否意味着这段代码是闭包?还是 MDN 错了?

最佳答案

MDN 是正确的,闭包是函数及其对其外部环境的引用(允许它访问该环境的内容)的组合。另见 the Wikipedia entry . (笼统地说,闭包是一个函数,它具有对其外部环境的引用。)

您在 SO 上从其他地方引用的文字似乎略有偏差,但概念很难解释。

But if MDN is right,

var a=1;
function printA(){
console.log(a);
}

this code include a function printA() and its lexical environment(variable a), does it mean this code is closure?

是的。事实上,JavaScript 中的所有 函数都是闭包(或者更准确地说,所有函数都与闭包相关联)。这就是全局变量的工作方式,因为所有函数都是全局词法环境的闭包。


作为实现优化,JavaScript 引擎有时可以优化函数与外部词法环境的链接,例如:

function double(a) {
return a * 2;
}

double 中没有任何内容是指在为调用 double 创建的词法环境中未定义的任何标识符,因此智能引擎可以(并且确实)优化掉链接完全。其他时候,他们可以确定只有部分外部环境被使用,因此只保留那些,允许其他人被垃圾收集。

关于javascript - MDN 上 JavaScript 闭包的定义是不是错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50529400/

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