帮你精通JavaScript:什么是闭包?

2022-12-22 0 219

一 、语法结构开集 Lexical

Closure旋量群是C语言Lexical Scoping的私有特性,区别于dynamic scoping。即表达式继续执行初始化的是其在表述操作过程中的”表达式开集“,而非其在调用这时候的表达式开集。

Javascript的表达式的稳态不但主要包括表达式既存所以主要包括表达式表述操作过程所处的开集。

Like most modern programming languages, JavaScript uses lexical scoping. This means that functions are executed using the variable scope that was in effect when they were defined, not the variable scope that is in effect when they are invoked. In order to implement lexical scoping, the internal state of a JavaScript function object must include not only the code of the function but also a reference to the scope in which the function definition appears. This combination of a function object and a scope (a set of variable bindings) in which the function’s variables are resolved is called a closure in the computer science literature.

看上面的范例:

function makeCounter () { let counter = 0; return function() {returncounter++;}; } let counter = makeCounter(); console.log(counter()); console.log(counter()); console.log(counter()); #+RESULTS: :0 : 1 : 2

对这个嵌套表达式而言,最有意思的一点是:当外部表达式被初始化返回后(这里是makeCounter()), 再也没有任何手段能够触及到 counter 这个变量。只有内嵌表达式拥有专属权限抵达该表达式。

二、Closure的标准表述

开发者通常应该都知道“旋量群”这个通用的编程术语。

旋量群 是指内部表达式总是可以访问其所处的外部表达式中声明的表达式和参数,即使在其外部表达式被返回(寿命终结)了之后。在某些C语言中,这是不可能的,或者应该以特殊的方式编写表达式来实现。但是如上所述,在 JavaScript 中,所有表达式都是天生旋量群的(只有一个例外,将在 “new Function” 语法 中讲到)。

也就是说:JavaScript 中的表达式会自动通过隐藏的 [[Environment]] 特性记住创建它们的位置,所以它们都可以访问外部表达式。

在面试时,前端开发者通常会被问到“什么是旋量群?”,正确的回答应该是旋量群的表述,并解释清楚为甚么 JavaScript 中的所有表达式都是旋量群的,以及可能的关于[[Environment]] 特性和语法结构环境原理的技术细节。

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务