The understanding and role of closure

1. Scope of variables

To understand closures, you must first understand JavaScript's special variable scope.
There are nothing more than two scopes of variables: global variables and local variables.

The special thing about the Javascript language is that global variables can be read directly inside the function.

var n = 999;
function f1(){
  alert(n);
}
f1(); // 999

On the other hand, local variables within a function cannot be read naturally from outside the function.

function f1(){    
  var n = 999;
}
alert(n); // error

There is one thing to note here. When declaring variables inside a function, you must use the var command.
If you don't use it, you are actually declaring a global variable!

function f1(){
  n = 999;
}
f1();
alert(n); // 999
2. How to read local variables from the outside?
function f1() {
  var n = 999;
  function f2() {
    alert(n);
  }
  return f2;
}
var result = f1();
result(); // 999

Since f2 can read the local variables in f1, as long as f2 is used as the return value, can't we read its internal variables outside f1?

3. The concept of closure

The f2 function in the previous section of code is a closure.
My understanding is,A closure is a function that can read the internal variables of other functions.

Since in the Javascript language, only subfunctions inside the function can read local variables, closures can be simply understood asA function defined inside a function.
So, in essence, closure is a bridge connecting the inside of the function with the outside of the function.

4. The use of closures

Closures can be used in many places. It has two greatest uses. One is to read the variables inside the function as mentioned earlier, and the other is to keep the values ​​of these variables in memory.

How to understand it? Please look at the code below.

function f1() {
  var n = 999;
  nAdd = function () { n += 1 }
  function f2() {
    alert(n);
  }
  return f2;
}
var result = f1();
result(); // 999
nAdd();
result(); // 1000

In this code, result is actually the closure f2 function. It was run twice, the first time the value was 999, the second time the value was 1000. This proves that the local variable n in function f1 is always stored in memory and is not automatically cleared after f1 is called.

Why is this so?

The reason is that f1 is the parent function of f2, and f2 is assigned to a global variable, which causes f2 to always be in memory, and the existence of f2 depends on f1, so f1 is always in memory and will not be deleted after the call is completed. , recycled by the garbage collection mechanism (garbage collection).

Another thing worth noting in this code is that

  • "nAdd=function(){ n+=1 }" In this line, first of all, the var keyword is not used before nAdd, so nAdd is a global variable, not a local variable.
  • Secondly, the value of nAdd is an anonymous function, and the anonymous function itself is also a closure, so nAdd is equivalent to a setter that can operate on local variables inside the function outside the function.
5. Points to note when using closures

Since closures will cause the variables in the function to be stored in memory, which consumes a lot of memory, closures cannot be abused, otherwise it will cause performance problems on the web page, and may lead to memory leaks in IE. The solution is to delete all unused local variables before exiting the function.

Closures change the values ​​of variables inside the parent function outside the parent function. Therefore, if you use the parent function as an object, the closure as its public method, and the internal variables as its private value, you must be careful not to Feel free to change the value of the variable inside the parent function.

6. Classic closure interview questions

Problem: I want to pop up the corresponding number subscript 0~4 every time I click on the corresponding target, but actually the number 5 will pop up no matter which target is clicked.

function onMyLoad() {
  var arr = document.getElementsByTagName("p");
  for (var i = 0; i < arr.length; i++) {
    arr[i].onclick = function () {
      alert(i);
    }
  }
}

The problem: the onclick of each item in arr is a function instance (Function object). This function instance also generates a closure domain. This closure domain refers to the variables of the external closure domain, and the closure of its function scope The object has a reference named i. If the contents of the private variables in the outer closure field change, the value obtained by the inner closure field will naturally change.

Solution one

Solution: Add several corresponding closure domain spaces (anonymous functions are used here), specifically used to store the content (subscript) that originally needs to be referenced, but only for basic types (basic type value transfer, object type reference transfer) ).

//声明一个匿名函数,若传进来的是基本类型则为值传递,故不会对实参产生影响,
//该函数对象有一个本地私有变量 arg(形参) ,该函数的 function scope 的 closure 对象属性有两个引用,一个是 arr,一个是 i
//尽管引用 i 的值随外部改变 ,但本地私有变量(形参) arg 不会受影响,其值在一开始被调用的时候就决定了
for (var i = 0; i < arr.length; i++) {
  (function (arg) {
    arr[i].onclick = function () {
      // onclick 函数实例的 function scope 的 closure 对象属性有一个引用 arg,
      alert(arg);
      //只要 外部空间的 arg 不变,这里的引用值当然不会改变
    }
  })(i); //立刻执行该匿名函数,传递下标 i (实参)
}
Solution 2

Solution: Bind the event to the function returned by the newly added anonymous function. At this time, the reference arg of the closure object in the function scope of the bound function points to the private variable arg of the anonymous function that returns it.

for (var i = 0; i < arr.length; i++) {
  arr[i].onclick = (function (arg) {
    return function () {
      alert(arg);
    }
  })(i);
}
Solution three

Use the ES6 new syntax let keyword

for (var i = 0; i < arr.length; i++) {
  let j = i; // 创建一个块级变量
  arr[i].onclick = function () {
    alert(j);
  }
}

Guess you like

Origin blog.csdn.net/shanghai597/article/details/132056637