温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript中什么是闭包

发布时间:2021-07-01 18:00:16 来源:亿速云 阅读:118 作者:Leah 栏目:web开发

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI