RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
JavaScript闭包的含义是什么

本文小编为大家详细介绍“JavaScript闭包的含义是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“JavaScript闭包的含义是什么”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

创新互联是一家专注于成都网站设计、做网站与策划设计,灵璧网站建设哪家好?创新互联做网站,专注于网站建设十载,网设计领域的专业建站公司;建站业务涵盖:灵璧等地区。灵璧做网站价格咨询:18980820575

 一 、词法定义域 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://sczitong.cn/article/gsshci.html