javascript闭包

The Closure is a collection of all variables in scope at the time of function creation. To use closure, create a function inside another function which is called a Nested Function. The inner function will have access to the variables in the outer function scope (Closure helps to access the outer function scope), even after the outer function has returned. Closures are created every time a function is created.

闭包是函数创建时范围内所有变量的集合。 要使用闭包,请在另一个称为嵌套函数的函数内创建一个函数。 内部函数将有权访问外部函数范围中的变量( Closure有助于访问外部函数范围),即使在返回外部函数之后也是如此。 每次创建函数时都会创建闭包。

Before moving on to understand about Closures, let’s first get the big picture about Scope Chain in JavaScript.

在继续了解闭包之前,让我们首先了解一下JavaScript中的作用域链。

Normally, there are 2 types of scope:

通常,有两种类型的范围:

  • Global Scope全球范围
  • Local Scope当地范围

In ES5 version, a variable inside a function is not visible outside. But variables inside a block (conditions like if or while) are visible outside too.

在ES5版本中,函数内部的变量在外部不可见。 但是,块内部的变量(条件如if或while)也可以在外部看到。

From this, ES5 has function scope. There is no block scope.

由此,ES5具有功能范围。 没有阻止范围。

Edited on: 9th May 2019

编辑于:2019年5月9日

According to ES5, using functions were the only way to declare a block scope in code.

根据ES5 ,使用函数是在代码中声明块作用域的唯一方法。

But, in ES6 it was eased by let & const keywords which provides block scope.

但是,在ES6中,通过提供块范围的letconst关键字简化了操作。

Anyhow, Its better to have a knowledge on how JavaScript evolved step by step.

无论如何,最好了解JavaScript如何逐步发展。

Lets continue this in ES5 version :

让我们在ES5版本中继续:

var a = 10;
function app(){var b = 2;console.log(a); // 10console.log(b); // 2
}
console.log(b); //   ReferenceError: b is not defined
app();

As we already know, a is a Global variable & b is a local variable which is specific to the app function.

众所周知, a是全局变量, b是局部变量, 特定于app函数。

We can’t get the value of a local variable out of the local scope.

我们无法从本地范围获得本地变量的值。

使用嵌套函数—函数内部的函数 (Using a Nested Function — Function inside a Function)

var a = 10;
function app(){var b = 2;var d = 3;function add(){var c = a + b;}return add;
}
var x = app();
console.dir(x);

Here, the app is the parent function & add function is the child function.

在这里,应用程序是父功能,添加功能是子功能。

  • Rather than using console.log, console.dir is used to console all the properties of a specified JavaScript object which helps developers get the properties of that object

    而不是使用的console.log,console.dir用来安慰指定JavaScript对象,它可以帮助开发者获取对象的属性的所有属性

  • Variable x is assigned to app function & the app function returns the add function. Therefore we could see all the object properties of the add function.变量x被分配给app函数,而app函数返回add函数。 因此,我们可以看到add函数的所有对象属性。

If you see the console in the browser, you could see the Closure object inside the Scopes array.

如果在浏览器中看到控制台,则可以在Scopes数组中看到Closure对象。

Since the inner function add accesses the outer function variables b & d, those 2 variables will be added to the Closure object for the reference.

由于内部函数add访问外部函数变量b和d ,因此这两个变量将添加到Closure对象中以供参考。

Let’s have look at the next example for Closure:

让我们看一下Closure的下一个示例:

var a = 10;
var startFunc;
function app(){var b = 2;function add(){var c = a + b;console.log(c);}startFunc = add();
}
app(); // Invoke the app function
startFunc;
// as the app function invoked above will assign the add function to startFunc & console the value of c
  • a Global function called startFunc is assigned to the add function which is a child function of the parent app function.将一个名为startFunc的全局函数分配给添加函数,该函数是父应用程序函数的子函数。
  • This is possible only after the app function is invoked, otherwise startFunc will act as a global variable without any value assigned仅在调用app函数之后才有可能,否则startFunc将充当全局变量而未分配任何值

闭包在JavaScript中的应用 (Application of Closures in JavaScript)

Most of us use Closures while coding but we don’t get why we are using it. JavaScript doesn’t have the access modifiers like private, public, protected like other Object Oriented Programming Languages. So, we have to use functions to protect the namespace from the outside code usage in ES5.

我们大多数人在编码时都使用Closures,但我们不知道为什么要使用Closures。 JavaScript没有像其他面向对象的编程语言那样具有私有,公共,受保护的访问修饰符。 因此,我们必须使用函数来保护名称空间免受ES5中外部代码的使用。

Especially in functions, Immediately-invoked Function Expression (IIFE) is the one which is executed immediately after the declaration. You don’t need to invoke the function after the function is declared.

特别是在函数中, 立即调用函数表达式(IIFE)是在声明后立即执行的函数 。 声明函数后,无需调用该函数。

IIFE enables to write Module Pattern (one of the Design Pattern) in JavaScript.

通过IIFE,可以用JavaScript编写模块模式 (设计模式之一)。

Syntax definition of IIFE is:

IIFE的语法定义为:

(function(){//variables & scope that inside the function
})();

Let’s have an example:

让我们举个例子:

var studnetEnrollment = (function () {//private variables which no one can change//except the function declared below.var count = 0;var prefix = "S";// returning a named function expressionfunction innerFunc() {count = count + 1;return prefix + count;};return innerFunc;
})();
var x = studnetEnrollment(); // S1
console.log(x);
var y = studnetEnrollment(); // S2
console.log(y);

count & prefix are the 2 private variables which can’t be changed by anyone & can only be accessible to the inner function (here its innerFunc). This access is possible only by the feature called Closure.

count和prefix是2个私有变量,任何人都不能更改,并且只能由内部函数(此处为innerFunc)访问。 只有通过称为“关闭”的功能才能进行此访问。

  • At the first time, when the studentEnrollment function is called, the count variable inside the function is incremented 1 by innerFunc function.第一次调用StudentEnrollment函数时,函数内部的count变量将由innerFunc函数加1。
  • At the second time, the count is incremented the previous value of count which is 1 to 2在第二次,该计数增加计数的先前值,即1到2
  • These are possible by the Closure feature.通过关闭功能可以做到这些。

结论 (Conclusion)

The Closure is a collection of variables in an outer function which gives access to the inner function scope to protect the global namespace.

闭包是外部函数中变量的集合,外部函数可以访问内部函数范围以保护全局名称空间。

Closures enable developers to write clean code like OOP Languages which doesn’t confuse the global & local variable names in ES5 version.

闭包使开发人员可以编写干净的代码(如OOP语言),而不会混淆ES5版本中的全局和局部变量名称。

Happy Coding…….!!!!!

快乐编码……。!!!!!!!!

翻译自: https://www.freecodecamp.org/news/a-basic-guide-to-closures-in-javascript-9fc8b7e3463e/

javascript闭包

javascript闭包_JavaScript闭包基本指南相关推荐

  1. javascript闭包_JavaScript闭包教程–带有JS闭包示例代码

    javascript闭包 Closures – many of you JavaScript devs have probably heard this term before. When I sta ...

  2. javascript原型_JavaScript原型初学者指南

    javascript原型 You can't get very far in JavaScript without dealing with objects. They're foundational ...

  3. JavaScript基础系列---闭包及其应用

    闭包(closure)是JavaScript中一个"神秘"的概念,许多人都对它难以理解,我也一直处于似懂非懂的状态,前几天深入了解了一下执行环境以及作用域链,可戳查看详情,而闭包与 ...

  4. 让你分分钟学会Javascript中的闭包

    Javascript中的闭包 前面的话: 闭包,是 javascript 中重要的一个概念,对于初学者来讲,闭包是一个特别抽象的概念,特别是ECMA规范给的定义,如果没有实战经验,你很难从定义去理解它 ...

  5. Javascript闭包和闭包的几种写法及用途

    好久没有写博客了,过了一个十一长假都变懒了,今天总算是恢复状态了.好了,进入正题,今天来说一说javascript里面的闭包吧!本篇博客主要讲一些实用的东西,主要将闭包的写法.用法和用途.  一.什么 ...

  6. 全面理解Javascript闭包和闭包的几种写法及用途【转】

    一.什么是闭包和闭包的几种写法和用法 1.什么是闭包 闭包,官方对闭包的解释是:一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分.闭包的特点: 1. ...

  7. 全面理解Javascript闭包和闭包的几种写法及用途

     一.什么是闭包和闭包的几种写法和用法 1.什么是闭包 闭包,官方对闭包的解释是:一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分.闭包的特点: 1. ...

  8. 全面理解Javascript闭包和闭包的几种写法及用途--转载自https://www.cnblogs.com/yunfeifei/p/4019504.html...

    全面理解Javascript闭包和闭包的几种写法及用途 好久没有写博客了,过了一个十一长假都变懒了,今天总算是恢复状态了.好了,进入正题,今天来说一说javascript里面的闭包吧!本篇博客主要讲一 ...

  9. 深入理解javascript原型和闭包(16)——完结

    之前一共用15篇文章,把javascript的原型和闭包. 首先,javascript本来就"不容易学".不是说它有多难,而是学习它的人,往往都是在学会了其他语言之后,又学java ...

最新文章

  1. vue 高阶面试题_高级Web前端工程师面试之Vue问题汇总解析
  2. [转] 用Firebug调试JavaScript
  3. POJ-1845 Sumdiv 逆元,特殊情况
  4. linux shc shell脚本_详解shell脚本加密解密软件—gzese和shc
  5. plsql轻量版游标的使用2
  6. Java Web文件下载
  7. 一步一步学Silverlight 2系列(5):实现简单的拖放功能_转载
  8. Mac如何修改文件默认打开方式?
  9. 技术升级成为Linux运维人前途的魔障,是跟进还是选择被淘汰?
  10. Chapter 15 电商产品评论数据情感分析
  11. STM32 通用 Bootloader
  12. spring data jpa 出现Not a managed type
  13. Microsoft Word 教程:如何在 Word 中创建项目符号列表、显示字数统计?
  14. 电脑系统故障维修,系统C盘满了怎么办?教你c盘清理方法
  15. 模板编码方法(template method)
  16. PHP如何在照片下面写一行字_怎样在手机照片下方留白加文字?
  17. 从酷狗的网络红歌说起
  18. (一)JAVA基于OPENXML的word文档插入、合并、替换操作系列之基础篇
  19. adobe flash player 过期问题
  20. kotlin中的var和val与编译时常量

热门文章

  1. OPENWRT的串口初试
  2. 2021.03.14.浩楠卷子
  3. 字节缓冲流 BufferedOutputStream java
  4. sqlserver增删改格式整理 1123
  5. 阿里云 快照恢复的操作过程
  6. 前端开发 认识css 体验变色的效果 0228
  7. python-带参数的装饰器
  8. linux-目录查询命令-目录内容查看-ls查询-tree查询-查询类容分类-不同颜色对应不同类型
  9. 网站迁移或者调整页面链接的方法
  10. redis 6.0 redis-proxy搭建