Nanyi is the interpretation of the closure in Javascript correct?

Source: Internet
Author: User
Nanyi has a popular article on JavaScript closures:
Learn JavaScript closures (Closure)

Feel very good, considering the previous was Pauling spray very miserable, so began to doubt the blog post explanation is correct.

Some points in the blog:
1. My understanding is that closures are functions that can read other functions ' internal variables.
2. Since in the JavaScript language, only sub-functions inside functions can read local variables, closures can be simply understood as "functions defined inside a function".
3. Closures can be used in many places. Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times.

Reply content:

Some of the laws are Kan, but there is no need to spray them.
Like what:
when declaring variables inside a function, be sure to use the var command. If not, you're actually declaring a global variable!
Instead of using Var, there is no sound change, but rather a visit to the window's nature.
And in the context of the variable in the window, it is possible to delete a variable that is directly stated in the global scope without being able to delete the change in the content of the window.

window.b = "HI";b; //"HI"Delete b; //Trueb; //Referenceerror:b is not defined(function(){C = "HI"}());C; //"HI"Delete C; //TrueC; //REFERENCEERROR:C is not definedvar a = "HI";a; //"HI"Delete a; //Falsea; //"HI"
"Some of the laws are correct, but there is no need to spray them," Kan said. "The anonymous answer at the beginning is right.

The concept of closures is actually derived from functional languages.

var a = function () {  var test = {};  setTimeout(function () {    console.log(test);  }, 1000);}
Nanyi's article is his study notes, not guaranteed to be all right, because it is only his understanding, and this article was written by him 09 years ago, perhaps his level is worse than now.
However, the content of his article is still relatively high, and because it is his study notes, so we read it easy to understand. Many beginners can go from the Nanyi to the high level, but things that are easy to understand are generally not rigorous. A rigorous article is very good, but it is not conducive to beginners understanding. Why do you say that, the rigorous concept will contain a lot of very vague terminology for beginners, such as the above answer to the main cosx mentioned: The closure is a function and its related to the context of the environment together. (the original sentence could be: A "closure" is an expression (typically A function) that can has free variables together with an environment that Binds those variables (that "closes" the expression). If you are a beginner, I believe that if you see a function, the relevant environment and other words, then directly ignorant.
But Nanyi says: Closures are functions that can read other functions ' internal variables. So, as long as the brain is moving, it should be possible to understand what a closure is. Even if this sentence is not rigorous.
So said Ruan a peak of the article is still worth seeing, his article can bring you into a field, but want to know this field correctly, you still need to read, this is also the difference between the network article and the physical book.
----------------------------------------------
To completely correct the understanding of closures, or to see COSX, Pauling answer, but to save enough basic knowledge. Closures are in the function UseOf not defined in functionOf but a variable (identifier) that is valid in the context of the functionand a collection of function ontologies. Or a little more rigorous. The closure is really the most difficult thing to understand JS, the nature of closures can be said to be formed by the scope chain
To understand closures, these concepts must be understood
1. Lexical scopes
2. Execution context
3. Active objects
4.scope Properties

Suppose the following code
function A (arg1) {
var v1=1;
var b=function b () {///executes to this line defines function B, avoids variable elevation problems with an expression
}
}
A ();
When a function B is defined (declared), it is in the running State (the execution context points to function a) in the previous layer of function A in the code tree, at which point the function B generates a scope property (the function nature is also an object, you can define the property), B.scope is an array, but through the code is not accessible, through the Chome debug panel can be seen, the attention of the classmate can be found that the active object of a push a (if a has a layer of functions, will push in in turn), at this time b.scope=[{v1:1}], The active object of the current function contains a variable of all var declarations in the body of a function, and the variable in the active object of B is first looked up when the variable is found inside function B, and if not, the parent function activity object in the Scope property array is traversed.

Because only at runtime code can declare functions, each function in the declaration, the parent function must be in the state of execution, recursive thinking, that the scope chain is entirely determined by the nesting sequence of functions, this is the meaning of the lexical scope, look at a function scope, as long as the static analysis of the structure of the code tree is OK.
The so-called scope chain, in fact, is implicitly the scope property of the first-level reference to the variable object of the previous layer of function, variable object lookup process, the principle and object properties through the __PROTO__ prototype chain lookup process is similar. A closure is a spy that enters the enemy's interior, through which you can contact the enemy's external blockade information. To mention some more personally thinkIt's a misleading place!

the special point of the JavaScript language is that the global variables can be read directly inside the function.
It's like other object-oriented languages don't.

on the other hand, a local variable inside a function cannot be read naturally outside the function.
The key is not mentioned at all, why can't I read the internal variables? The function destroys its internal environment after execution, which is not mentioned.

Sixth study Questions:
If you can understand the results of the following two sections of code, you should understand the operation mechanism of the closure.
var name = "The Window";  var object = {    name : "My Object",    getNameFunc : function(){      return function(){        return this.name;      };    }  };  alert(object.getNameFunc()());
What is a closure package?

Closures are not a novelty, as they have been in the early years of the development of high-level languages. Closures (Closure) are abbreviations for lexical closures (Lexical Closure). There are many ways to define closures, which can be broadly divided into two categories:

    • One argument is that closures are functions that meet certain conditions, such as defining closures in reference resources: Closures are functions that reference free variables (note 1) in their lexical context .
    • Another argument is that closures are entities that are composed of functions and their associated reference environment. For example, There is a definition in the reference resource: When implementing a deep constraint (Note 2), you need to create something that can explicitly represent a reference environment , and bundle it with the associated subroutine so that the whole bundle is called a closure.

These two definitions are antagonistic in a sense, one thinks that closures are functions and the other is that closures are the whole of functions and reference environments. Although some of the semantics, but certainly the second statement is more accurate. Closures are just like functions in form and expression, but are not actually functions. Functions are executable code that is determined after the function is defined and does not change at execution time, so there is only one instance of a function. Closures can have multiple instances at run time, and different reference environments and the same combination of functions can produce different instances. The so-called reference environment is a collection of all active constraints at a point in the execution of a program. The constraint refers to the relationship between the name of a variable and the object it represents. So why combine the reference environment with the function? This is mainly because in languages that support nested scopes, it is sometimes not straightforward to determine the reference environment of a function directly. Such a language generally has such a feature:

    • A function is a first-order value (first-class value), that is, a function can be a return value or parameter of another function, and can also be used as the value of a variable.
    • Functions can be defined in a nested definition, meaning that another function can be defined inside a function.
1&2: Closures are used to describe the ability of that function to access that variable. Instead of that function, it's not that variable. The ability of a function to access variables outside its lexical scope.
3: Permanently saved in memory? Just extend the life of the object to the same function that uses it. If all the functions that use it are recycled, the variable is recycled. (Well, in practice, this is a dead-eye, but also to see how the JS engine implementation)

The role of closures in JS:
Hide Private variables
Pass the extra parameters to the run-time generated function (because your generated function will be called by someone else, such as a callback function, there is no doubt that the number and order of the parameters of the function are fixed, but your function does need more information)

Issues to be aware of:
Once a variable enters the closure, it is copied to the heap, and all use of the variable is resolved to refer to the variable in the heap. Therefore, all functions that use this variable will be read to the most recent value, not the value that you created the function.

In fact, a professional point in the JS book is explained.
  • 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.