1. Review the scope of variables

Variables can be divided into two types depending on their scope: global variables and local variables.

  1. Global variables can be used inside functions.
  2. Local variables may not be used outside functions.
  3. Local variables in this scope are destroyed when the function completes execution.

2. What are closures

A closure is a function that has access to variables in the scope of another function. Simply put, a scope can access local variables inside another function.

3. Debug closures in Chrome

  1. Open your browser and press F12 to launch the Chrome debugger.
  2. Set breakpoints.
  3. Find the Scope option.
  4. When we refresh the page, we will enter breakpoint debugging, and the Scope will have two parameters (global global Scope, local local Scope).
  5. When fn2() is executed, a Closure argument is added to the Scope, indicating that a Closure has been generated.

4. What closures do

Action: Extend the scope of action of variables.

 function fn() {
   var num = 10;
   function fun() {
       console.log(num);
 	}
    return fun;
 }
var f = fn();
f();
Copy the code

5. The closure case

  1. Use closure to get the current li index
for (var i = 0; i < lis.length; Function (I) {lis[I].onclick = function() {if (lis[I].onclick = function() {if (lis[I].onclick = function() { console.log(i); } })(i); }Copy the code
  1. Closure application – After 3 seconds, print the contents of all li elements
 for (var i = 0; i < lis.length; i++) {
   (function(i) {
     setTimeout(function() {
     console.log(lis[i].innerHTML);
     }, 3000)
   })(i);
}
Copy the code
  1. Closure application – Calculate taxi fares
/* Demand analysis Taxi fare starts at 13(within 3 kilometers) and increases by 5 yuan for each additional kilometer. */ var start = (function() {var start = 13; Var total = 0; Price: function(n) {if (n <= 3) {total = start; } else { total = start + (n - 3) * 5 } return total; Yd: function(flag) {return flag? total + 10 : total; }}}) (); console.log(car.price(5)); // 23 console.log(car.yd(true)); / / 33Copy the code

Case 6.

var name = "The Window"; var object = { name: "My Object", getNameFunc: function() { return function() { return this.name; }; }}; console.log(object.getNameFunc()()) ----------------------------------------------------------------------------------- var name = "The Window"; Var object = {name: "My object ", getNameFunc: function() {var that = this; return function() { return that.name; }; }}; console.log(object.getNameFunc()())Copy the code