What is a closure package:
The sum of "functions" and "variables (also called environments) that can be accessed inside a function is a closure."
JavaScriptThere are two types of scopes: global scope and function scope. The global variable can be read directly inside the function. However, variables declared inside the function cannot be read outside the function. In other words, if a function uses a variable outside its scope, then ' This function + this variable ' is called a closure.
function F1 () { var n = 1; function F2 () { console.log (n); } return // in this code, the sum of the function F2 and the variable n is called the closure
Use of closures:
1. Read the variables inside the function from the outside.
function F1 () { var n = 9; function F2 () { console.log (n); } return var result =/// 9// in this code, the return value of the function F1 is the function F2, Since F2 can read the internal variables of the F1, it is possible to obtain F1 internal variables externally.
2. Keep these variables in memory at all times.
function F1 (n) { returnfunction () { return n++; };} var a1 = F1 (1// 1// 2// 3 // in this code, the closure allows internal variables to remember the result of the last call.
3. Encapsulates the private properties and private methods of the object.
functionF1 (n) {return function () { returnn++; };}varA1 = F1 (1); A1 ()//1A1 ()//2A1 ()//3varA2 = F1 (5); A2 ()//5A2 ()//6A2 ()//7//in this code, A1 and A2 are independent of each other and return their own private variables.
Call:call is the normal invocation of the function and specifies the context of this.
The Apply:apply function is the same as call, but the arguments are transmitted in different ways. The difference is that apply accepts an array parameter, and call accepts a continuous parameter. The following code:
function Add (A, b ) {return A +//8//8
Bind:bind accepts parameters consistent with call, but Bind is not immediately called, it will generate a new function, when you want to tune when the tune. The following code:
function Add (A, b) { return a +b;} var foo1 = Add.bind (add, 5,3//8var foo1 = Add.bind (add, 5,3 // 8
Closures, closures, use of call, apply, bind