In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to analyze the concept of closure in JS, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
Closure is a difficulty and feature of Javascript language. Many high-level applications rely on closures.
1. Scope of variables
To understand closures, you must first understand the special variable scope of Javascript.
The scope of variables is nothing more than two kinds: global variables and local variables.
The special feature of Javascript language is that global variables can be read directly inside the function.
Var nasty 999; function F1 () {alert (n);} F1 (); / / 999
On the other hand, it is naturally impossible to read local variables within the function outside the function.
Function F1 () {var nude 999;} alert (n); / / error
One thing to note here is that when declaring variables inside a function, be sure to use the var command. If not, you actually declare a global variable!
Function F1 () {nasty 999;} F1 (); alert (n); / / 999
2. How to read local variables from the outside
For a variety of reasons, we sometimes need to get local variables within a function. However, as mentioned earlier, under normal circumstances, this cannot be done, and it can only be achieved through flexible methods.
That is to define another function inside the function.
Function F1 () {alert 999; function f2 () {alert (n); / / 999}}
In the above code, function f2 is included within function F1, and all local variables within F1 are visible to f2. But not the other way around. The local variables inside f2 are invisible to F1. This is the "chain scope" structure peculiar to Javascript language (chain scope).
Child objects look up for variables for all parent objects level by level. Therefore, all variables of the parent object are visible to the child object, and vice versa.
Since f2 can read local variables in F1, as long as we take f2 as the return value, we can read its internal variables outside F1!
Function f1 () {function f2 () {alert (n);} return f2;} var result=f1 (); result (); / / 999
3. The concept of closure
The f2 function in the last section of the code is the closure.
The definition of "closure" in various professional literature is very abstract and difficult to understand. My understanding is that a closure is a function that can read internal variables of other functions.
Because in the Javascript language, only the subfunctions inside the function can read local variables, the closure can be simply understood as "a function defined inside a function".
So, in essence, a closure is a bridge that connects the inside of a function to the outside of a function.
4. The use of closures
Closures can be used in many places. It has two greatest uses, one is to read variables within the function mentioned earlier, and the other is to keep the values of these variables in memory all the time.
How to understand this sentence? Please look at the code below.
Function f1 () {var nude 999; nAdd=function () {alert (n)} function f2 () {alert (n);} return f2;} var result=f1 (); result (); / / 999 nAdd (); result (); / / 1000
In this code, result is actually a closure f2 function. It runs twice, the first with a value of 999 and the second with a value of 1000. This proves that the local variable n in function F1 is kept in memory all the time and is not automatically cleared after F1 call.
What causes it? The reason is that F1 is the parent function of f2, and f2 is assigned to a global variable, which causes f2 to always be in memory, while the existence of f2 depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call.
Another noteworthy aspect of this code is that the line "nAdd=function () {nailed variables 1}" first does not use the var keyword before nAdd, so nAdd is a global variable, not a local variable. Second, the value of nAdd is an anonymous function (anonymous function), and this
The anonymous function itself is also a closure, so nAdd is equivalent to a setter and can operate on local variables inside the function outside the function.
5. Attention points for using closures
1) because the closure will make the variables in the function be stored in memory, which consumes a lot of memory, the closure should not be abused, otherwise it will cause performance problems of web pages and may lead to memory leakage in IE. The solution is to delete all unused local variables before exiting the function.
2) the closure will change the value of the internal variable of the parent function outside the parent function. So, if you use the parent function as an object (object), the closure as its common method (Public Method), and the internal variable as its private property (private value), you must be careful not to change the value of the internal variable of the parent function.
6. Thinking questions
If you can understand the running results of the following code, you should understand how closures work.
Var name = "The Window"; var object = {name: "My Object", getNameFunc: function () {return function () {return this.name;};}}; alert (object.getNameFunc () ()); / / The Window
Example of JS closure:
Function outerFun () {var astato; function innerFun () {astatine; alert (a);}} innerFun ()
The above code is incorrect. The scope of innerFun () is inside outerFun (), and it is wrong to call it outside outerFun ().
Change it to the following, that is, closure:
Function outerFun () {var astato; function innerFun () {astatine; alert (a);} return innerFun; / / notice here} var obj=outerFun (); obj (); / / result is 1obj (); / / result is 2var obj2=outerFun (); obj2 (); / / result is 1obj2 (); / / result is 2
What is a closure:
When an internal function is referenced outside the scope that defines it, a closure of the internal function is created. If the internal function references variables located in the external function, these variables will not be released in memory when the external function is called. Because closures need them.
Example:
Function outerFun () {var a = 0; alert (a);} var axiom 4 politics outerFun (); alert (a)
The result is 0BI 4. Because the var keyword is used inside the function to maintain the scope of a within outFun ().
Take a look at the following code:
Function outerFun () {/ / there is no var a = 0; alert (a);} var axi4umbent alert ()
It's strange that the result is zero. Why?
Scope chain is a term that describes a path along which the value of a variable can be determined. When executing astat0, because the var keyword is not used, the assignment operation follows the scope chain to var axiom 4; and changes its value.
If you don't have a good understanding of javascript closures, take a look at the following reprinted article:
What is a closure?
The official explanation is that a closure is an expression (usually a function) that has many variables and the environment that binds them, so these variables are part of the expression. I believe that few people can directly understand this sentence, because his description is too academic. In fact, the popular saying is: all function in JavaScript is a closure. In general, however, the closures produced by nested function are more powerful and are what we call "closures" most of the time. Look at the following code:
Function a () {var I = 0; function b () {alert (+ + I);} return b;} var c = a (); c ()
This code has two characteristics:
1. Function b is nested inside function a
2. Function a returns function b.
The reference relationship is shown in the figure:
So after executing var Centra (), the variable c actually points to the function b, and then executing c () will pop up a window showing the value of I (1 for the first time). This code actually creates a closure. Why? Because the variable c outside function a refers to function b within function a, that is to say:
When the inner function b of function an is referenced by a variable outside function a, a closure is created.
Let's be more thorough. The so-called "closure" is to define another function as the method function of the target object in the constructor body, which in turn refers to the temporary variable in the outer function body. This makes it possible to indirectly maintain the value of the temporary variable used by the original constructor body as long as the target object maintains its method throughout its lifetime. Although the original constructor call has ended and the names of temporary variables have disappeared, the value of the variable can always be referenced within the method of the target object, and the value can only be accessed through this method. Even if the same constructor is called again, only new objects and methods are generated, and the new temporary variables just correspond to the new values, independent of the last call.
Second, what is the function of closures?
In short, the function of closures is that after an is executed and returned, the closure ensures that Javascript's garbage collection mechanism GC will not recover the resources occupied by a, because the execution of a's internal function b depends on variables in a. This is a very straightforward description of the role of closures, unprofessional and unrigorous, but that's what it probably means. Understanding closures requires a step-by-step process.
In the above example, due to the existence of the closure, the I in an always exists after the function a returns, so that every time c () is executed, I is the value of alert I since the addition of 1.
So let's imagine another situation, if a doesn't return function b, the situation is completely different. Because after the execution of a, b is not returned to the outside world of a, but is referenced by a, and at this time a will only be referenced by b, so the functions an and b refer to each other but are not disturbed by the outside world (referenced by the outside world), and the functions an and b will be recycled by GC. (the garbage collection mechanism of Javascript will be described in more detail later.)
III. The microscopic world in the closure
If we want to have a deeper understanding of closures and the relationship between function an and nested function b, we need to introduce several other concepts: function execution environment (excution context), active object (call object), scope (scope), scope chain (scope chain). Take the process of function a from definition to execution as an example to illustrate these concepts.
When defining a function, the js interpreter sets the chain of scope (scope chain) of function a to the "environment" in which an is defined. If an is a global function, there are only window objects in the scope chain. When the function an is executed, an enters the corresponding execution environment (excution context). In the process of creating the execution environment, you will first add a scope attribute to a, that is, the scope of a, whose value is scope chain in step 1. That is, the domain chain of a.scope=a. The execution environment then creates an active object (call object). The active object is also an object with properties, but it does not have a prototype and cannot be accessed directly through JavaScript code. After creating the active object, add the active object to the top of a's scope chain. At this time, the scope chain of a contains two objects: the active object and the window object. The next step is to add an arguments property to the active object, which holds the parameters passed when function an is called. Finally, the formal parameters of all the functions an and the references of the internal function b are also added to the active object of a. In this step, the definition of function b is completed, so as in step 3, the scope chain of function b is set to the environment in which b is defined, that is, the scope of a.
At this point, the whole function an is completed from definition to execution. At this time, a returns a reference to function b to c, and the scope chain of function b contains a reference to the active object of function a, that is, b can access all variables and functions defined in a. Function b is referenced by c, and function b depends on function a, so function a will not be reclaimed by GC after it is returned.
When the function b is executed, it will be the same as the above steps. Therefore, the scope chain of b at execution time contains three objects: the active object of b, the active object of a, and the window object, as shown in the following figure:
As shown in the figure, when accessing a variable in function b, the search order is:
First search for its own active object, if it exists, return, if it does not exist, it will continue to search for the active object of function a, and then search until it is found. If there is a prototype prototype object in function b, then look for its own prototype object after finding its own active object, and then continue to find it. This is the variable lookup mechanism in Javascript. If it cannot be found on the entire scope chain, undefined is returned.
In summary, two important words are mentioned in this paragraph: the definition and execution of functions. It is mentioned that the scope of a function is determined when the function is defined, not when it is executed (see steps 1 and 3). Use a piece of code to illustrate the problem:
Function f (x) {var g = function () {return x;} return g;} var h = f (1); alert (h ())
The variable h in this code points to the anonymous function in f (returned by g).
Assuming that the scope of the function h is determined by executing alert (h ()), then the scope chain of h is: h's active object-> alert's active object-> window object. Suppose the scope of the function h is determined at the time of definition, that is, the anonymous function that h points to has already determined the scope at the time of definition. So at execution time, the scope chain of h is: h's active object-> f's active object-> window object.
If the first hypothesis is true, the output value is undefined;. If the second hypothesis is true, the output value is 1.
The running results prove that the second hypothesis is correct, indicating that the scope of the function is indeed determined when the function is defined.
Fourth, the application scenario of closure protects the security of variables in the function. Taking the initial example, I in function a can only be accessed by function b and cannot be accessed by other means, thus protecting the security of I.
Maintain a variable in memory. As in the previous example, I in function an is always in memory because of the closure, so I is incremented by 1 every time c () is executed. Implement JS private properties and methods (which cannot be accessed externally) by protecting the security of variables. Private properties and methods are inaccessible outside Constructor
Function Constructor (...) {var that = this; var membername = value; function membername (...) {...}}
The above three points are the most basic application scenarios of closures, which are the source of many classic cases.
5. Garbage collection mechanism of Javascript
In Javascript, if an object is no longer referenced, the object is reclaimed by GC. If two objects refer to each other and are no longer referenced by the third party, the two objects that reference each other will also be recycled. Because function an is referenced by b, b is referenced by c outside a, which is why function an is not recycled after execution.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.