JS closures

What is a closure?

  1. To understand closures, you must first understand the scope of special variables in Javascript.

  2. How to read the internal variables of the function from the outside?

function test() {
  var num = '88888';
  function test2() {
     console.log(num)  
  }    
}

  In the above code, we will find that the test2 function is included in the test function, and all the local variables in test are visible to test2, but the local variables in test2 are invisible to the test function.

       The test2 function at this time is the closure.

  After understanding the following sentence, you can basically understand the closure.

  Functions in Javascript run in the scope where they are defined, not the scope where they are executed.

Points to note when using closures:

  1. The variables of the functions used in the closure are stored in the memory, which consumes a lot of memory. Avoid abuse of the closure, which will cause performance problems of the web page. solve

  Solution: Before exiting the function, clear all unused local variables

  2. The closure will change the value of the parent function outside the parent function. It should be noted that do not change the value of the parent function casually.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325131553&siteId=291194637