This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

preface

A closure is a combination of a function and the lexical context in which it is declared, which contains any local variables that were in scope when the closure was created. — Source MDN latest explanation 🤞

The characteristics of

  1. A closure is a function.
  2. In the case of destruction of the external function context, free variables in the scope of the external function can still be accessed.

example

function say() {
    let name = 'jin line'
    function hello() {
        console.log('hello,' + name)
    }
   return hello
}
let func = say()
func() / / hello, jin
Copy the code

From the example, when let func = say() is finished, although the execution context of say function has been recycled and destroyed, the execution result can still read the value of name variable.

Closures and chains of scope

In theory, the variable value cannot be read after the execution context has been destroyed. Don’t forget, however, that a chain of scopes is maintained while creating a function execution context. When a closure function references a local variable of an enclosing function, JavaScript keeps the enclosing function lexical environment alive in memory and the closure function can still find it through the scope chain, even if the enclosing function context is destroyed.

performance

It is unwise to create a function within a function if it is not required for a specific task, because closures have a negative impact on scripts in terms of processing speed and memory consumption.

When creating a new object or class, the methods should normally associate with the object’s prototype, rather than being defined in the object’s constructor. Because every time the constructor is called, the method is reassigned.

example

function func(name) {
    this.name = name.toString()
    this.getName = function() {
        return this.name
    }
}
Copy the code

The above code, which does not take advantage of closures, should be modified as follows:

function func(name) {
    this.name = name.toString()
}
func.prototype = {
    getName: function() {
        return this.name
    }
}
Copy the code

reference

Closures JavaScript deep closure