帮你精通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" 语法 中讲到)。

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

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

展开阅读全文

页面更新:2024-03-19

标签:定义域   词法   嵌套   本体   开发者   变量   术语   语法   函数   寿命   属性   也就是说   例子   手段   定义

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top