An introduction to closures in JavaScript

  • 2020-05-16 06:19:51
  • OfStack

A closure is when an internal function reads a variable other than the current function, which is the context in which it was created.


function hello(){
    var char = "hello,world";
    function print(){
        console.log(char);
    };
    return print();
}

Note that the print function here refers to the char variable of the external hello function, so here we can return 1

hello,world

And this functionality, in a sense, is due to scope. Of course, there is no way to access char directly, unless we made a mistake in declaring the variable. Such as

function hello(){
    char = "hello,world";
    function print(){
        console.log(char);
    };
    return print();
}

Just because there's an var missing.


Here, hello become 1 A closure . Closures are 1 Kind of a special object. It consists of two parts: the function and the environment in which it is created. The environment consists of any local variables that were in scope when the closure was created.

Javscript closure and this

It is important to note that reading this and arguments can cause problems.


function hello(){
    this.char = "hello,world";
    function output(){
        char = "I'm no hello world";      
        console.log(this.char);
    };
    return output();
}

Of course, this example is not appropriate enough, so, we need an additional example to explain this problem, the following is a quote from Javascript advanced programming, an example to illustrate this problem.

var name = "The window"; var object = {
    name: "My Object",     getNameFunc: function(){
        return function(){
            return this.name;
        }
    }
};
object.getNameFunc()()

It's just that this usage is true, and the solution is to save a temporary variable, that, as described earlier in "some knowledge of this for Javascript" 1.


var name = "The window";
var object = {
    name: "My Object",     getNameFunc: function(){
        var that = this;
        return function(){
            return that.name;
        }
    }
};
object.getNameFunc()()

Javscript closures with read-write variables
It's worth noting that we can modify our variables if we don't handle them properly.

function hello(){
    var char = "hello,world";
    return{
        set: function(string){
            return char = string;
        },
        print: function(){
            console.log(char)
        }
    }
}
var say = hello();
say.set('new hello,world')
say.print() // new hello world

Javascript closures and performance

To quote MDC


  If closures are not required for some particular task, it is unwise to create functions in other functions when they are not necessary, because closures have a negative impact on script performance, including processing speed and memory consumption.

The text also says.

  For example, when creating a new object or class, the method should usually be associated with the prototype of the object, not defined in the constructor of the object. The reason is that this causes the method to be reassigned every time the constructor is called 1 Times (that is, for each 1 Object creation).


Related articles: