Home  >  Article  >  Web Front-end  >  What are closures in Javascript

What are closures in Javascript

小云云
小云云Original
2017-11-20 15:28:541150browse

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

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

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();

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();

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:
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