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

 一 、帮精闭包词法定义域 Lexical

Closure闭包是帮精闭包编程语言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() {return counter++;}; } let counter = makeCounter(); console.log(counter()); console.log(counter()); console.log(counter()); #+RESULTS: : 0 : 1 : 2 

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

二、源码下载帮精闭包Closure的帮精闭包标准定义

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

闭包 是帮精闭包指内部函数总是可以访问其所在的外部函数中声明的变量和参数,即使在其外部函数被返回(寿命终结)了之后。帮精闭包在某些编程语言中,帮精闭包这是帮精闭包不可能的,或者应该以特殊的方式编写函数来实现。但是如上所述,在 JavaScript 中,所有函数都是天生闭包的(只有一个例外,将在 "new Function" 语法 中讲到)。IT技术网

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

在面试时,前端开发者通常会被问到“什么是闭包?”,正确的回答应该是闭包的定义,并解释清楚为什么 JavaScript 中的所有函数都是闭包的,以及可能的关于 [[Environment]] 属性和词法环境原理的技术细节。

应用开发
上一篇:探索IntelCorem7Y30处理器的卓越性能与创新潜力(深入解析Corem7Y30处理器的关键特性及应用前景)
下一篇:微鲸电视调声音技巧大揭秘(让你的观影体验更加舒适,微鲸电视调声音方法大公开)