How can we explain in plain js inside the 'closure'?

Read on to know the topic of peace  How can we explain in plain javascript inside the 'closure'? , By some inspiration, so the answer with examples in several essence of the answer to do a simple analysis for a better understanding.

1. "closure is the scope of cross access variables." 

Example [a]

var name = 'wangxi'
function user () {
  // var name = 'wangxi'
  function getName () {
    console.log(name)
  }
  getName()
}
the User () // wangxi

Get in getName function name, first looks at the role of the domain name getName function is not found, then look in the scope user function, the same is not found, continue to back up, found name in the global scope, and therefore get name and prints. Here it is well understood that the variables exist in the specified scope, if you can not find the desired variable in the current role, to continue to look at the parent scope through the scope chain until you find the first one with the same name variable up to (or can not be found, thrown ReferenceError error) . This is the concept js in the scope chain, that is a child scope can access the parent variable scope of the scope chain, if it does the opposite, the parent scope would like to access the variable sub-scope of it? - This needs to be achieved through closure.

Example [two]

function user () {
  var name = 'wangxi'
  return function getName () {
    return name
  }
}

var userName = user()()
console.log(userName) // wangxi

We know that the code analysis, the variable name is present in the topical scope of user functions, under normal circumstances, outside scope (global here) it is unable to access to the variable name, but by the closure (function returns a variable containing here is the getName function), you can access the cross-scoped variables (external access to internal). Therefore, this statement above should be understood as complete:

Scope closure is the cross access variables - the internal reference domain variable scope may be maintained so that the effect of the external (more) variables can be accessed outside the scope of the internal scope. (Or do not understand the words look a analysis)

 

2. "closure: father performed in an environment grandfather, my father returned a grandson, my father had been executed over, the father of the environment should be removed, but cited his father's grandson environment, leading to the release of the father can not lump is closure. simply put, the closure is a reference to the object's parent environment, and the environment from the parent returns to a higher-level objects in the environment. "

How this understanding it? First look at the code below:

function user () {
  var name = 'wangxi'
  return name
}

var userName = user()
console.log(userName) // wangxi

Q : This is a closed bag?

Answer : Of course not. We must first understand what a closure yes. Although formal point of view seems also visited local variables within the user function in the global scope name, but the problem is, executing the user, name also will be destroyed, that the life cycle of local variables within a function exists only in the statement periodic function, the function is destroyed, variable within the function is automatically destroyed.

But the use of closures on the contrary, the function is executed, the end of the life cycle, but by the closure variable references outer scope still exists and will exist until the implementation of the closure of the scope is destroyed, local variables here (scopes will be destroyed if the closure cited references closure in the global environment, only to be destroyed in the global environment, such as the end of the program, close the browser and other acts) it will be destroyed. Therefore, in order to avoid closure due to memory loss, it is recommended to manually destroyed after use closures. Or the above two exemplary example, minor modifications:

function user () {
  var name = 'wangxi'
  return function getName () {
    return name
  }
}

var userName = the User () () // userName variable name has always maintained a reference to 
console.log (userName) // wangxi 

userName = null  // destroy closure, the release of memory

[Why user () () are two brackets: execution user () function returns the getName, to get the name variable, you need to perform a getName function returns, it is the user () ()]

According to Point 2 , analyze the code: create in the global scope of the userName variable (grandfather), saved to user function eventually returns the result of reference (ie, the value of a local variable name), to perform user () () (father), return the name (grandson), under normal circumstances, after the execution of the user () (), user environment (the father) should be removed, but because the results returned by name (grandson) quoted the father of the environment (because the name could have been is present in the user's scope), leading to user's environment can not be released (can cause memory loss).

So [ "closure is a reference to the object's parent environment, and the environment from the parent returns to a higher-level objects in the environment."] How to understand?

We put it another way: If a function references a parent objects in the environment, and in this function to return the object to a higher level of environment, then this function is closure.

Or look at the example above:

getName function referenced object user (parent) environment (variable name), and the function name is returned to the global environment variables (more senior environment), therefore, is getName closure.

3. "JavaScript function runs in the scope they are defined, rather than being carried out in their scope." - "JavaScript The Definitive Guide"

This sentence is very helpful for understanding closure references to variables. We look at the following example:

var name = 'Schopenhauer'
function getName () {
  console.log(name)
}

function myName () {
  var name = 'wangxi'
  getName()
}

myName() // Schopenhauer

If you do myName () and output the results you think are not the same, you have to go back and look at the above said, this sentence,

JavaScript function runs in the scope they are defined, rather than the scope in which they are performed

MyName execution, internal function performed getName, and getName is defined in the global environment, although the definition of a variable in myName the name, does not affect the implementation of the getName, getName in print is still under the name of global scope.

We slightly changed the code below:

var name = 'Schopenhauer'

function getName () {
   var name = 'Aristotle'
    var Intro = function () {   // This is a closure 
      the console.log ( 'the I AM' + name)
   }
   return intro
}

function showMyName () {
   var name = 'wangxi'
   var myName = getName()
   myName()
}

showMyName() // I am Aristotle

Results and you think the same? The results of your analysis is reserved for smart ~

 

Above is the understanding of the js closures, if wrong, please correct me. Finally, a reference to answer questions about the concept of closure of the section almost known problem.

( Author: Xiao Xiao  links: https://www.zhihu.com/question/34547104/answer/197642727 )

What is closure?

Briefly, the closure means functions can access another function scope variables typically define the inner function layer function.

Why do we need closure?

Local variables can not be shared and long-term preservation, and global variables may cause pollution variables, so we hope to have a mechanism for long-term preservation both variable and will not cause global pollution.

Feature

  • Take up more memory
  • Not easy to be released

When to use?

Variables both want to re-use, we want to avoid global pollution

how to use?

  1. Define the outer function, local variables packages are protected.
  2. Define the inner function, operation function of the external variables.
  3. The function returns the object function inner layer and an outer layer function is called, the result is stored in a global variable.

Guess you like

Origin www.cnblogs.com/ITCodeMonkey/p/11672557.html