JS in the "Closure"? In-depth javascript

Source: Internet
Author: User

How can you explain the ' closures ' in JavaScript by reading the topic? , inspired by a simple analysis of the answers to a few of the essentials in an example to deepen understanding.

1. "Closures are accessing variables across scopes. "

"Example One"

var name = ' Wangxi ' function user () {  //var name = ' Wangxi '  function GetName () {    console.log (name)  }
   
    getname ()}user ()//Wangxi
   

Get name in the GetName function, first in the scope of the GetName function to find the name, not found, and then in the scope of the user function to find, also not found, continue to backtrack, found in the global scope exists name, so get the name value and print. It is well understood here that the variable exists in the specified scope, and if the desired variable is not found in the current action, the lookup continues through the scope chain to the parent scope until the first variable with the same name is found (or cannot be found, throwing a referenceerror error). This is the concept of the scope chain in JS, that is, the child scope can access variables in the parent scope based on the scope chain, and if so, in the parent scope, do you want to access the variables in the child scope? -This needs to be done through closures.

"Example Two"

function User () {  var name = ' Wangxi '  return function getName () {    return name  }}var userName = User () () c Onsole.log (UserName)//Wangxi

Parsing code We know that name is a local variable that exists within the scope of the user function, and normally it is inaccessible to the name variable in the outer scope (in this case, the global), but through the closure (which returns a function that contains the variable, here is the GetName function), You can implement cross-scope access to variables (external access inside). Therefore, the above statement should be understood as complete:

Closures are access variables across scopes--internal scopes can maintain references to variables in the outer scope so that (more) external scopes can access variables in the inner scope. (or do not understand the words to see the next analysis)

2. "Closure: In the grandfather's environment to carry out the father, father returned to the grandson, the father was executed, Dad's environment should be cleared away, but the grandson cited the father's environment, resulting in dad can not release." This lump is a closure. Simply put, a closure is an object that references the parent environment and returns from the parent environment to an object in a higher-level environment. "

How does that make sense? First look at the code below:

"Example three"

function User () {  var name = ' Wangxi '  return name}var userName = User () Console.log (userName)//Wangxi

Q : Is this a closed bag?

answer : Of course not. The first thing to understand is what closures are. Although it looks like it also accesses local variables within the user function under the global scope name, the problem is that when user executes, name is destroyed, that is, the lifetime of the local variable within the function is only in the declaration period of the function, the function is destroyed, and the variables inside the function are automatically destroyed.

With closures, however, the function finishes, the end of the life cycle, but the variables in the outer scope referenced by the closure still exist and will persist until the scope of the execution closure is destroyed and the local variables are destroyed (if the closure is referenced in the global environment, only if the global environment is destroyed, The scope of the closure reference is only destroyed when the program finishes, the browser shuts down, and so on. Therefore, in order to avoid the memory loss caused by closures, it is recommended to manually destroy them after using closures. As an example of example two above, make a slight change:

"Example Four"

function User () {  var name = ' Wangxi '  return function getName () {    return name  }}var userName = User () () A reference to name is always maintained in the UserName variable Console.log (userName)//Wangxiusername = NULL//Destroy closure, free memory

"Why User () () is two parentheses: execution user () returns the GetName function, and to get the name variable, it needs to be executed once for the returned getName function, so it is User () ()"

According to Point 2, analyze the code: Create a UserName variable under the global scope (grandpa), save a reference to the result of the user function's final return (that is, the value of the local variable name), execute User () () (dad), and return Name (grandson), normally, after user () () is executed, the user's environment (dad) should be erased, but because the returned result name (grandson) refers to the environment of the father (because name is already in the scope of user), causing the user Environment cannot be released (which can cause memory loss).

Then the "" Closure is an object that references the parent environment and returns from the parent environment to an object in the higher-level environment. "How to understand?"

Let's put it another way: if a function refers to an object in the parent environment and returns the object to a higher-level environment in this function, then the function is a closure.

Or look at the example above:

The GetName function refers to the object in the user (parent) environment (the variable name), and the name variable is returned to the global environment (higher-level environment) in the function, so getName is the closure.

3. "The functions in JavaScript run in their defined scopes, not in the scopes they are executed in." "--The JavaScript authoritative guide"

This sentence is useful for understanding the references to variables in closures. Let's look at the following example:

var name = ' Schopenhauer ' function getName () {  console.log (name)}function MyName () {  var name = ' Wangxi '  getn Ame ()}myname ()//Schopenhauer

If the result of executing the myName () output is different from what you think, you'll have to go back and look at the words.

The functions in JavaScript run in their defined scopes, not in the scopes they are executed in.

Executing MyName, the getName is executed inside the function, and getName is defined in the global context, so although the variable name is defined in MyName and has no effect on the execution of GetName, the getName print is still the name under the global scope.

Let's change the code a little bit:

var name = ' Schopenhauer ' function getName () {var name = ' Aristotle '   var intro = function () {  //This is a closure      cons Ole.log (' I am ' + name)   }   return intro}function showmyname () {   var name = ' Wangxi '   var myName = Getnam E ()   myName ()}showmyname ()//I AM Aristotle

Is it the same as you think? The result is to stay smart and analyze yourself ~

The above is the JS in the closure of the understanding, if wrong, welcome to correct. Finally, an answer to the concept of closure is quoted under the question of knowledge.

(萧潇 Link: https://www.zhihu.com/question/34547104/answer/197642727)

What is a closure package?

In a nutshell, a closure is a function that accesses another function-scoped variable, typically an inner-layer function that defines an outer-layer function.

Why do I need closures?

Local variables cannot be shared and persisted, and global variables can cause variable contamination, so we want a mechanism that can persist variables for long periods without causing global pollution.

Characteristics

    • Use more memory
    • Not easy to be released

When to use?

Variables that want to be reused and avoid global pollution

How do I use it?

    1. Defines an outer function that encapsulates a protected local variable.
    2. Defines an inner-layer function that performs an operation on an external function variable.
    3. The outer function returns an object of the inner layer function, and the outer function is called, and the result is stored in a global variable.

Reference

On the closure and scope chain of JavaScript

Plot the scope of JavaScript by a problem

How can you explain the ' closures ' in JavaScript in an understandable way?

In-depth JavaScript this JS in the "Closure"?

JS in the "Closure"? In-depth javascript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.