Detailed explanation of js closures, you will know after reading

First come a piece of closure code

function outerFunction() {
    
    
  var outerVariable = "I am defined in outerFunction";

  function innerFunction() {
    
    
    console.log(outerVariable);
  }

  return innerFunction;
}

var inner = outerFunction();
inner(); // 输出 "I am defined in outerFunction"

In this example, outerFunctiona function that contains an inner function innerFunction. outerFunctionIn , we define a local variable outerVariableand innerFunctionaccess it in .

innerFunctionouterFunctionis defined in and returned. outerFunctionWhen we call , it returns innerFunctiona reference to , which is assigned to the variable inner.

When we innercall , it actually calls innerFunction, and accesses outerVariable. Although outerFunctionhas finished executing and returned, innerFunctionis stillouterVariable accessible because it still holds a reference to in its lexical environment.outerVariable

This capability is achieved through closures: innerFunction capturing and saving a reference outerVariable to a so that outerVariableit can outerFunctionstill be accessed after execution is complete.

First, what is a closure?

Closure means 有权访问另一个函数作用域中变量的函数that even if this function has finished executing and returns. can 通过返回一个函数或者把函数作为参数传递给另一个函数来创建闭包. Closures can capture variables of external functions, and these variables can be accessed and manipulated within the closure, which makes closures can be used in many scenarios, such as encapsulating variables, implementing modularization, and caching data.

2. The realization principle of closure

In JavaScript, a function can access variables in the scope in which it was defined. When a function is defined, it creates a new scope and contains itself within it. This new scope is called "function scope" or "lexical scope". When a variable is referenced in a function, the JavaScript engine first looks for the variable in the function scope. If it doesn't find the variable in the function scope, it will keep looking in the outer scope until it finds the variable.

When a function is nested inside another function, 内部函数可以访问外部函数的变量. If the inner function survives after the outer function returns, and the variable is still accessible, the variable will continue to exist in memory. This is because the inner function still retains a reference to its original scope, preventing the garbage collector from clearing that variable out of memory.

3. The role of closure

Closures have many important uses in JavaScript, such as:

1. Package variables

Closures can encapsulate variables in a private scope, preventing them from being accessed and modified externally. This is one way of implementing "private variables" in object-oriented programming.

2. Mock private methods

Closures can be used to simulate private methods in a class. A private method refers to a method that can only be accessed inside the class, which can hide some implementation details and improve the maintainability and security of the code.

3. Memory context

Closures can be used to remember the context of a function. For example, in JavaScript, the setTimeout function creates a new scope, causing the function's this value to change. Closures can be used to save the context of the function and use it in the setTimeout callback function.

4. Prevent pollution of the global namespace

Closures prevent pollution of the global namespace. In JavaScript, all variables belong to the global scope. If you accidentally define a global variable, it may conflict with other variables. Closures can be used to encapsulate variables in private scopes, thereby avoiding

Fourth, the advantages and disadvantages of closures

1. Advantages

  • Private variables and functions can be created inside functions to avoid variables polluting the global scope.
  • The value of the internal variable of the function is preserved, and the variable of the external function can be accessed, thus expanding the scope and flexibility of the function.
  • Can be used to implement private variables and methods similar to object-oriented programming.
  • Can help improve code modularity and reusability.

2. Disadvantages

  • Memory usage: Since closures retain references to the external environment, memory is not released when not needed, which may lead to memory leaks.
  • Performance issues: Because closures involve accessing external variables, there will be a certain performance loss.
  • Poor readability: Using closures will increase the complexity of the code, making it difficult to understand and maintain.
  • Security issues: If variables in closures are misused or tampered with, it can lead to security issues.

Guess you like

Origin blog.csdn.net/weixin_46369590/article/details/129862595