javascript闭包_JavaScript闭包基本指南

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); // 10
   console.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 expression
     function 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闭包

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值