Table of Contents
1. What is a closure?
2. Advantages, disadvantages and characteristics of closures in JS
3. Variable scope
4. Interpret closures with code
五、如何从外部读取函数内部的局部变量?
六、闭包的用途
七、使用闭包的注意点
八、总结:
Home Web Front-end Front-end Q&A What is a closure in javascript

What is a closure in javascript

Oct 18, 2021 am 11:59 AM
javascript Closure

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

What are the advantages and disadvantages of closures in C++ functions? What are the advantages and disadvantages of closures in C++ functions? Apr 25, 2024 pm 01:33 PM

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

Solve the memory leak problem caused by closures Solve the memory leak problem caused by closures Feb 18, 2024 pm 03:20 PM

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

The impact of function pointers and closures on Golang performance The impact of function pointers and closures on Golang performance Apr 15, 2024 am 10:36 AM

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

How are closures implemented in Java? How are closures implemented in Java? May 03, 2024 pm 12:48 PM

Closures in Java allow inner functions to access outer scope variables even if the outer function has exited. Implemented through anonymous inner classes, the inner class holds a reference to the outer class and keeps the outer variables active. Closures increase code flexibility, but you need to be aware of the risk of memory leaks because references to external variables by anonymous inner classes keep those variables alive.

Chained calls and closures of PHP functions Chained calls and closures of PHP functions Apr 13, 2024 am 11:18 AM

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

Summary of the advantages and disadvantages of golang anonymous functions and closures Summary of the advantages and disadvantages of golang anonymous functions and closures May 05, 2024 am 09:54 AM

Anonymous functions are concise and anonymous, but have poor readability and are difficult to debug; closures can encapsulate data and manage state, but may cause memory consumption and circular references. Practical case: Anonymous functions can be used for simple numerical processing, and closures can implement state management.

See all articles