JavaScript中什么是闭包-成都快上网建站

JavaScript中什么是闭包

这篇文章给大家介绍JavaScript中什么是闭包,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

成都创新互联10多年成都定制网页设计服务;为您提供网站建设,网站制作,网页设计及高端网站定制服务,成都定制网页设计及推广,对成都自上料搅拌车等多个方面拥有多年的网站设计经验的网站建设公司。

 一 、词法定义域 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中什么是闭包就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


文章标题:JavaScript中什么是闭包
文章网址:http://kswjz.com/article/ippsji.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流