What is a closure in javascript

青灯夜游
Release: 2021-11-24 13:40:04
Original
2159 people have browsed it

In JavaScript, when two functions are nested within each other, the inner function is a closure. A closure is a function that has access to variables in the scope of another function. The most common way to create a closure is to create another function within a function and access the local variables of this function through the other function.

What is a closure in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

1. What is a closure?

A closure is a function that can read the internal variables of other functions. In JavaScript, only subfunctions inside a function can read local variables, so closures can be understood as "functions defined inside a function." In essence, closures are a bridge between the inside of a function and the outside of the function. (The most typical application of closures is to implement callback functions).

2. Advantages, disadvantages and characteristics of closures in JS

Advantages:

1 , Protect the security of variables within the function

2. Maintain a variable in the memory (using too much will become a disadvantage and occupy memory);

3. Logical continuity, when closure When used as a parameter in another function call, it prevents you from writing additional logic separately from the current logic.

4. Local variables that facilitate calling context.

5. Strengthening the encapsulation can protect variables.

Disadvantages:

1. Resident memory will increase memory usage, and improper use can easily cause memory leaks.
2. There is also a very serious problem, which is the problem of memory waste. This memory waste is not only because it resides in memory, but more importantly, improper use of closures will cause the generation of invalid memory.

Features:

1. Function nested functions

2. Internal functions can access variables of external functions

3. Parameters and variables will not be recycled.

3. Variable scope

To understand closure, it is not enough to only understand the concept of closure above. First, you must understand the special variable scope of JavaScript.

1. There are only two scopes of variables: global variables and local variables.

2. The special thing about the JavaScript language is that global variables can be read directly inside the function, but local variables inside the function cannot be read outside the function.

3. Note: When declaring variables inside a function, be sure to use the var command. If you don't use it, you are actually declaring a global variable!

4. Interpret closures with code

The creation process of closures in Javascript is as shown in the following program.

function a () {
   var i = 0;
   function b () {
      alert (i++);
   }
  return b;
}
var c = a();
c();  //函数调用
Copy after login

Code Features

This code has two features:

1. Function b is nested in function a Internal;

2. Function a returns function b.

In this way, after executing var c = a(), variable c actually points to function b. After executing c() again, a window will pop up to display the value of i (the first time is 1) . This code actually creates a closure because variable c outside function a refers to function b inside function a. In other words, when function b inside function a is referenced by a variable outside function a, a closure is created.

Function

In short, the function of the closure is to enable Javascript garbage collection after a is executed and returned. The mechanism will not reclaim the resources occupied by a, because the execution of a's internal function b needs to rely on the variables in a.

In the above example, due to the existence of closure, i in a will always exist after function a returns. In this way, every time c() is executed, i will be the value of i that is alerted after adding 1. .

Then let’s imagine another situation. If a returns something other than function b, the situation is completely different. Because after a is executed, b is not returned to the outside world of a, but is only referenced by a. At this time, a will only be referenced by b. Therefore, functions a and b refer to each other but are not disturbed by the outside world (referenced by the outside world). , functions a and b will be recycled.

Application Scenario

1. Protect the variables within the function. In function a, i can only be accessed by function b and cannot be accessed through other means, thus protecting the security of i.

2. Maintain a variable in memory. Due to the closure, i in function a always exists in memory, so every time c() is executed, i will be incremented by 1.

五、如何从外部读取函数内部的局部变量?

  出于种种原因,我们有时候需要获取到函数内部的局部变量。但是,上面(三、变量作用域)已经说过了,正常情况下,这是办不到的!只有通过变通的方法才能实现。那就是在函数内部,再定义一个函数。

function demo1 () {
    var n = 6699;
    function demo2 () {
      alert(n); // 6699
    }
  }
Copy after login

在上面的代码中,函数 demo2 就被包括在函数demo1内部,这时demo1内部的所有局部变量,对demo2都是可见的。但是反过来就不行,demo2内部的局部变量,对demo1就是不可见的。 

这就是Javascript语言特有的”链式作用域”结构(chain scope),子对象会一级一级地向上寻找所有父对象的变量。所以,父对象的所有变量,对子对象都是可见的,反之则不成立。 

既然demo2可以读取demo1中的局部变量,那么只要把demo2作为返回值,我们不就可以在demo1外部读取它的内部变量了吗!

六、闭包的用途

闭包可以用在许多地方。它的最大用处有两个,一个是前面提到的可以读取函数内部的变量,另一个就是让这些变量的值始终保持在内存中,不会在demo1调用后被自动清除。 

那为什么会这样呢?原因就在于demo1是demo2的父函数,而demo2被赋给了一个全局变量,这导致demo2始终在内存中,而demo2的存在依赖于demo1,因此demo1也始终在内存中,不会在调用结束后,被垃圾回收机制(garbage collection)回收。

七、使用闭包的注意点

1、由于闭包会使得函数中的变量都被保存在内存中,内存消耗很大,所以不能滥用闭包,否则会造成网页的性能问题,在IE中可能导致内存泄露。解决方法是,在退出函数之前,将不使用的局部变量全部删除。 

2、闭包会在父函数外部,改变父函数内部变量的值。所以,如果你把父函数当作对象(object)使用,把闭包当作它的公用方法(Public Method),把内部变量当作它的私有属性(private value),这时一定要小心,不要随便改变父函数内部变量的值。

八、总结:

1、闭包是指有权访问另一个函数作用域中的变量的函数,创建闭包的最常见的方式就是在一个函数内创建另一个函数,通过另一个函数访问这个函数的局部变量。闭包的缺点就是常驻内存,会增大内存使用量,使用不当很容易造成内存泄露。 

2、不适合场景:返回闭包的函数是个非常大的函数。 

    闭包的典型框架应该就是jquery了。 

    闭包是javascript语言的一大特点,主要应用闭包场合主要是为了:设计私有的方法和变量。 

    这在做框架的时候体现更明显,有些方法和属性只是运算逻辑过程中的使用的,不想让外部修改这些属性,因此就可以设计一个闭包来只提供方法获取。 

3、 不必纠结到底怎样才算闭包,其实你写的每一个函数都算作闭包,即使是全局函数,你访问函数外部的全局变量时,就是闭包
的体现。

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of What is a closure in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!