Home >Web Front-end >JS Tutorial >Easy understanding of JavaScript closures

Easy understanding of JavaScript closures

黄舟
黄舟Original
2017-03-20 14:48:572127browse

The closure mechanism is the focus and difficulty of JavaScript. This article hopes to help everyone learn closures easily. Let’s take a look at it with the editor

Abstract

The closure mechanism is the focus and difficulty of Javascript. This article hopes to help everyone learn closures easily

1. What is closure?

A closure is a function that can access variables in the scope of another function.

Common closure implementation methods are listed below, and the concept of closure is explained with examples

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

f1 is the parent function of f2, and f2 is assigned to a global variable (the value of return) , which results in f2 always being in memory, and the existence of f2 depends on f1, so f1 is always in memory and will not be recycled by the garbage collection mechanism (garbage collection) after the call is completed, which forms a closure.

So, it can be understood this way. The closure mechanism is that if function A references a variable of another function B, but A still does not return after B returns, it still exists. Because of A’s reference, all of B’s Local variables will not be logged out when B exits, and will always exist until A logs out. At this time A is the closure.

2. The this pointer of the closure

Closures are usually called in the global environment, so this usually points to the window, which is still needed in specific situations. Depending on the execution environment, in short, this points to the execution environment.

If you need the closure's this to point to the closure's containing object, you need to pass the containing object's this as a variable into the closure.

3. Points to note when using closures

  1. Because closures will cause all variables in the function to be stored in memory, memory consumption It is very large, so closures cannot be abused, otherwise it will cause performance problems on the web page and may cause memory leaks in IE. The solution is to delete all unused local variables before exiting the function.

  2. The closure will change the value of the variable inside the parent function outside the parent function. So, if you use the parent function as an object (object), the closure as its public method (Public Method), and the internal variables as its private properties (private value), you must be careful not to change the value of the internal variable of the parent function casually.

4. Solve a common closure interview question

Question:

function onMyLoad(){
  /*
  抛出问题:
  此题的目的是想每次点击对应目标时弹出对应的数字下标 0~4,但实际是无论点击哪个目标都会弹出数字5
  问题所在:
  arr 中的每一项的 onclick 均为一个函数实例(Function 对象),这个函数实例也产生了一个闭包域,
  这个闭包域引用了外部闭包域的变量,其 function scope 的 closure 对象有个名为 i 的引用,
  外部闭包域的私有变量内容发生变化,内部闭包域得到的值自然会发生改变
  */
  var arr = document.getElementsByTagName("p");
  for(var i = 0; i < arr.length;i++){
  arr[i].onclick = function(){
   alert(i);
  }
  }
 }

Solution

1. Add a layer of functions outside and pass i as the function parameter, so that each What is saved this time is the variable inside the function, which is not in the same memory space as the external i. Each time the function is called, a local variable is generated, so it can be guaranteed that the values ​​saved each time do not affect each other.

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

2. Use the new ES6 let, change the var i of for loop to let i, so that the current i is only valid in this cycle, so the i of each cycle is actually It's all a new variable. You may ask, if the variable i is redeclared in each cycle of the loop, how does it know the value of the previous cycle and thus calculate the value of this cycle? This is because the Javascript engine will internally remember the value of the previous cycle, and when initializing the variable i of this cycle, calculations will be performed on the basis of the previous cycle.

The above is the detailed content of Easy understanding of JavaScript closures. 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