In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "how to understand JavaScript closures", so the editor summarizes the following contents, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to understand JavaScript closures" article.
1. Closure self-knot
Closure concept:
After the function is executed, the result is an internal function and is cited by an external variable. If the internal function holds a variable in the domain of the holding function, a closure is formed. You can access the external function domain in the internal function.
Make the "closure" can read the variables in the function, and the variables in the function can be stored in memory to protect the variables from being contaminated. Because the closure will store the variable values in the function in memory, it will consume memory, so you can't overload the closure, otherwise it will affect the performance of memory and cause memory leakage. To release memory in time when you do not need to close, assign the variable of the inner function object to null.
Closure characteristics: multiple closure memory spaces generated by an external function are independent of each other.
Closure application scenarios:
Maintain variables in memory: if caching data, Corey
Protect variables within the function: such as iterators, generators.
Disadvantages: closures will cause the original scope chain not to be released, resulting in memory leakage.
Memory consumption has a negative impact. Because the internal function saves the reference to the external variable, the method is garbage collected, and the amount of memory is increased, so improper memory will lead to memory leakage.
It has a negative effect on the processing speed. The level of the closure determines the degree of domain chain through which the external variables are searched.
May get an unexpected value (captured value)
Advantages:
The variables in the operation domain of the external function can be accessed from the internal function, and the accessed variables are resident in memory for later use.
Avoid variables polluting the whole world
Save the variable to the unique operation domain and exist as a private member
two。 Closure concept
A function is bundled with a reference to its surrounding state (lexical environment, lexical environment) (or the function is surrounded by a reference). Such a combination is called a closure. That is, the closure allows you to access the scope of the outer function in an inner function. In JavaScript, whenever a function is created, the closure is created at the same time as the function is created.
Lexical scope
Take a look at the following code:
Function init () {var name = "Mozilla"; / / name is a local variable created by init function displayName () {/ / displayName () is an internal function, a closure alert (name); / / uses the variable declared in the parent function} displayName ();} init ()
Init () creates a local variable name and a function named displayName (). DisplayName () is an internal function defined in init () and is only available in the body of the init () function. Note that displayName () does not have its own local variable. However, because it can access variables of external functions, displayName () can use the variable name declared in the parent function init ().
After running the code using this JSFiddle link, it is found that the alert () statement in the displayName () function successfully shows the value of the variable name (which is declared in its parent function). This lexical scope example describes how the parser parses variable names when functions are nested. The word lexical means that the lexical scope determines where a variable is available based on the location of the declared variable in the source code. Nested functions can access variables declared in their external scope.
3. Looking at closures from the perspective of stack
The values of variables of basic data types are generally stored in stack memory, the basic data types: Number, Boolean, Undefined, String, Null. The values of variables of object type are stored in heap memory, and stack memory stores the corresponding space address.
Var a = 1 / / an is a basic data type var b = {m: 20} / b is an object
Corresponding memory storage:
When we execute b = {mbure30}, the heap memory has a new object {mbure30}, and the b of the stack memory points to the new space address (pointing to {mbure30}), and the original {mbure20} in the heap memory will be garbage collected by the program engine to save memory space. We know that js functions are also objects, and they are also stored in heap and stack memory, so let's take a look at the conversion:
Var a = 1 * * function fn () {var b = 2 function fn1 () {console.log (b)} fn1 ()} fn ()
The stack is a first-in-and-out data structure:
Before executing fn, we are in the global execution environment (the browser is the window scope), where there is a variable a
When you enter fn, the stack memory will push a fn execution environment, in which there are variables b and function object fn1, where you can access the variables defined by your own execution environment and the global execution environment.
When you enter fn1, the stack memory will push a fn1 execution environment, where no other variables are defined, but we can access the variables in fn and the global execution environment, because the program looks to the underlying stack one by one when accessing variables (this is the "chained scope" structure (chain scope) peculiar to Javascript language). If it finds no corresponding variables in the global execution environment, the program throws a underfined error.
With the completion of the execution of fn1 (), the execution environment of fn1 is destroyed, and then after the execution of fn (), the execution environment of fn is also destroyed. only in the global execution environment, there are no b variables and fn1 function objects, only an and fn (function declaration scope is under window).
Access to a variable within a function is based on the function scope chain to determine whether the variable exists, and the function scope chain is initialized by the program according to the execution environment stack where the function is located, so in the above example, we print variable b in fn1 and find the corresponding variable b in the fn execution environment according to the scope chain of fn1. So when a program calls a function, it does the following: prepare the execution environment, the initial function scope chain, and the arguments parameter object
Now let's take a look at the closure example.
Function outer () {var a = 'variable 1' var inner = function () {console.info (a)} return inner / / inner is a closure function because it can access the scope of the outer function} var inner = outer () / / get the inner closure function inner () / / "variable 1"
When the program finishes executing var inner = outer (), the execution environment of outer is not destroyed, because the variable an in it is still referenced by the function scope chain of inner. When the program finishes executing inner (), the execution environment of inner and outer will be destroyed. The book "JavaScript Advanced programming" suggests that because closures carry the scope of the functions that contain them, because they take up more content than other functions, excessive use of closures can lead to too much memory.
4. The problem of shared variables of closures
The following is to explain the problem of shared variables of closures through outer outer functions and inner inner functions.
How to determine whether multiple closures generated by the same outer function are independent spaces or shared spaces? Please look at the example first.
/ / when the first case is called, pass the variable value function outer (name) {return function () {console.log (name)} F1 = outer ('yang') f2 = outer (' fang') console.log (f1.toString ()) F1 () / / yang f2 () / / fangf1 () / / yang / / the second case: the local variable value of the external function is the change function count () {var arr = [] For (var iTunes 1; I
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.