JS a novice understanding of closures

The concept of closure

Closures function is the ability to read other function of the internal variables, in JS, only inside a function Functions can read local variables, which caused some inconvenience in use. The role of closure function is like a bridge as a function of the internal and external functions connected. Variables can be protected to avoid contamination.

Closure conditions present

  1. A direct or indirect internal function returns a function B
  2. B function uses an internal private variables inside a function of A / private data
  3. A function has a variable internal accept function B

Closure spaces

When the function execution, execution will open up a space, all the code will be executed in this space, after serving, this space will be automatically destroyed.
Closure function will not destroy a form of execution space (below) performs a function of space, called space closure. Wherein b-return function called a function closure function. (B function to access the private variables of a function)
but this does not destroy the implementation of space will cause the data cache, the performance impact of page (after using the need for timely release)
Function returns a

Case of the closure,

Array as a return value

When you return value is an array when the closure is formed. We define a res fn for receiving in return an array, this time to form a closure space, the console.log After implementation of a (res), performs spatial and will not disappear.
When we give res and defines when a "value" (let res points to another location), the function returns the internal complex data types will not be received, closure spaces will be destroyed, do console.log (res) again when you can not access the interior space of the fn.
Returns an array

About closures

There is closure package, to avoid adding too many global functions and global variables, reduce naming conflicts. Global avoid contamination. But the disadvantage is also evident closures, so we should be familiar with, at the time of application, even easier.

Novice

JS as a novice, there are a lot of knowledge is not enough to grasp firmly, trying to learn ing, more than it is my understanding that some of the closures, we hope a lot of corrections. A lot of criticism.

Released two original articles · won praise 0 · Views 29

Guess you like

Origin blog.csdn.net/AsuraThor/article/details/104460507