Home Web Front-end JS Tutorial What are closures in Javascript

What are closures in Javascript

Nov 20, 2017 pm 03:28 PM
javascript js Closure

What is closure?

What is closure? Closure is Closure, which is a new feature that static languages ​​do not have. But closure is not something that is too complicated to understand. In short, closure is: closure is the set of local variables of the function, but these local variables will continue to exist after the function returns. Closure means that the "stack" of a function is not released after the function returns. We can also understand that these function stacks are not allocated on the stack but on the heap. When another function is defined within a function, a closure will occur. Bag.

Closure = function created inside the function (or internal function for short) + environmental information when the function was created

So closure is not equal to anonymous function, although some people call these functions The function created internally is a closure function, but I think it is not accurate.

Let’s take a look at the following code:

function init() {
    var name = "Zilongshanren"; // name 是在 init 函数里面创建的变量
    // displayName() 是一个内部函数,即一个闭包。注意,它不是匿名的。
    function displayName() {
        console.log(name);
    }
    //当 displayName 函数返回后,这个函数还能访问 init 函数里面定义的变量。
    return displayName;
}
var closure = init();
closure();
Zilongshanren
undefined
Copy after login

displayName is a function created inside the init function. It carries all the information in the internal scope of the init function, such as the name variable here. When the displayName function returns, it itself carries the environment information when it was created, that is, the name variable in the init function.

What does closure do?

After understanding what a closure is, you may ask: This thing is so difficult to understand, what is its use?

Because there is no way to create private methods in JS. It is not like Java or C++ that has the private keyword to define private properties and methods. In JS, only functions can create objects belonging to their own scope. JS does not have block scope! I will write another article to introduce this in detail later.

Every programming veteran knows that to write a program well, encapsulation and abstraction must be used well! The inability to define private properties and methods means that encapsulation and abstraction cannot be used at all. . .

You cannot define private things, all variables and functions are public. Obviously there is a problem, Global is Evil!

Closures are our savior!

Let’s take a look at the following code:

var makeCounter = function() {
    var privateCounter = 0;
    function changeBy(val) {
        privateCounter += val;
    }
    return {
        increment: function() {
            changeBy(1);
        },
        decrement: function() {
            changeBy(-1);
        },
        value: function() {
            return privateCounter;
        }
    }
};
var counter1 = makeCounter();
var counter2 = makeCounter();
console.log(counter1.value()); /* Alerts 0 */
counter1.increment();
counter1.increment();
console.log(counter1.value()); /* Alerts 2 */
counter1.decrement();
console.log(counter1.value()); /* Alerts 1 */
console.log(counter2.value()); /* Alerts 0 */
0
2
1
0
undefined
Copy after login

The privateCounter variable and changeBy here are private and completely invisible to the outside of the makeCounter function. In this way, the object we generate through makeCounter hides all its private data and private methods.

Does this remind you of anything?

Haha, isn’t this just OO? Encapsulate data and methods for operating data, and then complete data processing through public interface calls.

Of course, you may say that I can also implement OO using prototypal inheritance. Yes, that’s what most people do now, including ourselves. However, inheritance is always very difficult to understand, because to understand a piece of code, you must understand all its inheritance chains. If there is a bug in the code, it will be very difficult to debug.

I’m going too far. Next, let’s look at how to use closures correctly.

How to use closures correctly?

Closures will occupy memory and also affect the execution efficiency of the js engine. Therefore, if a piece of code is executed frequently, you should carefully consider using closures in this code.

Let's look at a function that creates an object:

function MyObject(name, message)
 {    this.name = name.toString();  
   this.message = message.toString();   
    this.getName = function()
     {        return this.name;    };   
      this.getMessage = function() 
      {        return this.message;    };}
      var myobj = new MyObject();
var myobj = new MyObject();
Copy after login

Every time it is called to generate a new object, two closures will be generated. If there are thousands of such MyObject objects in your program, it will take up a lot more memory.

The correct approach should be to use the prototype chain:

function MyObject(name, message) {
    this.name = name.toString();
    this.message = message.toString();
}
MyObject.prototype.getName = function() {
    return this.name;
};
MyObject.prototype.getMessage = function() {
    return this.message;
};
var myobj = new MyObject();
Copy after login

Now the MyObject prototype defines two methods. When we create an object through new, these two methods will only be used in the prototype. There is a copy on it.

What is the performance of closures?

A closure is also a function, but it stores additional environment information, so theoretically it takes up more memory than a pure function, and the JS engine consumes more when interpreting and executing the closure. However, the performance difference between them is between 3% and 5% (this is the data obtained from Google, which may not be too accurate).

However, the benefits of closure are definitely great. Use closures and stateless programming more to keep bugs away from us.

Understand closures, and you will be able to understand most of the Js class libraries in the FP paradigm and the design ideas hidden behind them. Of course, closure is not enough. You also need to be brainwashed by concepts such as FP, statelessness, and lambda calculus.

About js closure, I hope everyone will have a grasp of it after finishing this article.

Related recommendations:

A simple explanation of closures in JS

How to understand closures and classes in JS

A simple understanding of js closure

The above is the detailed content of What are closures 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

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.

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.

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.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

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.

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.

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.

See all articles