5. Closure
Closure means that the inner function can reference variables that exist within the function surrounding it, even if the execution of the outer function has terminated.
Let’s first look at an example of closure.
]
Code ① is inside a function layer, but it can use the variable num of the outer layer.
Closure can also solve another common JS problem, the impact of global variables.
By automatically executing anonymous function combination closures, variables that are originally global can be hidden. Look at the example below:
If you need to introduce external Js, you need to refresh to execute
]
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute ]
The concept of closure is not easy to grasp, and it took me a lot of time and energy to understand it.
6. Summary
Notes (2), (3), and (4) explain several important contents in JavaScript, including references, function overloading, scope, context objects, and closures.
Key contents of reference: pointer, array reference, string reference, difference, pass by value, pass by address.
Key contents of function overloading: number of parameters, type of parameters, arguments, pseudo array, typeof, constructor, difference - string and object.
Key contents of scope: function division, global scope, global object, properties of window object, local scope, explicit declaration, implicit declaration.
Key contents of context object: this variable, call, apply, parameter difference, array.
Key contents of closure: inner function, outer function, variable, setTimeout, closure problem, last assignment, closure and scope.