Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand JavaScript closure

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to understand JavaScript closure, I believe that many inexperienced people are at a loss about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

In-depth analysis of JavaScript closures

What is a closure? ❝

A function is bundled with a reference to its surrounding state, and such a combination is a closure.

In popular terms, the scope in which an inner function can access an outer function is called a closure.

In JavaScript, whenever a function is created, the closure is created at the same time as the function is created.

The formation of closures is closely related to the scope and life cycle of variables. Characteristic ❝of ❞closure

Function nested function

External parameters and variables can be referenced inside the function

Parameters and variables will not be collected by the garbage collection mechanism

Advantages and disadvantages of ❞closure ❝

Advantages:

Private methods and variables can be designed

"shortcomings"

Resident memory, will increase memory usage, improper use is easy to cause memory leakage.

"after the execution of a general function, the locally active object is destroyed and only the global scope is saved in memory. "

❞on the scope of variables ❝

The scope of the variable: the valid scope of the variable.

In actual development, what we often encounter is the variable scope declared in the function. "

❞var a = 'closure'

Function getValue () {

Var a = 'function local scope'

Console.log (a)

}

GetValue () / / function local scope

When a variable with the same name is declared globally, and a variable with the same name is declared inside the function, the function has priority to access the variable in the scope of the function.

❞function scope ❝

Function scope: variables outside the function can be accessed inside the function, while variables outside the function cannot access variables inside the function.

Why?

"because when searching for a variable in a function, if there is no declaration of the variable inside the function, it will search layer by layer with the scope created by the execution environment of the code until the global variable is searched. "

The search for variables is searched from the inside out.

❞function getData () {

Var str = "closure exercise"

Var fun = function () {

Var innerStr = 'internal variable'

}

Console.log (innerStr)

/ / the outer layer of the innerStr is not defined function cannot access the inner layer variables of the function.

}

GetData ()

The life cycle ❝of a variable

For a global variable, its lifetime is permanent unless the variable is actively destroyed.

For the "function local variable", when the function is finished, the local variable will be destroyed.

❞Chestnut 1

Document

one

two

three

four

Var nodes = document.getElementsByTagName ('div')

For (var I = 0; I < nodes.length; iTunes +) {

Nodes [I] .onclick = function () {

Alert (I)

}

}

Add a click event to each div, and when you click div, pop up its corresponding index value.

Now no matter which div is clicked, it pops up with 4.

Why?

"because the div click event is triggered asynchronously, the loop is finished when the event is triggered, and the variable value of I is 4. "

How to solve the problem of clicking on each div to pop up the corresponding I value?

* * you can borrow the closure to save the I of each loop. When the click event is executed, it will search the scope of the variable from the inside to the outside, and it will first search the I of the closure environment. * *

❞# closure solution

Var nodes = document.getElementsByTagName ('div')

For (var I = 0; I < nodes.length; iTunes +) {

(function (I) {

Nodes [I] .onclick = function () {

Alert (I)

}

}) (I)

}

Chestnut 2var num = 1

Function getValue () {

Var num = 0

Return function () {

Num++

Console.log (num)

}

}

Var s = getValue ()

S ()

S ()

/ / 1 2

According to common sense: after the execution of the function, num = 1 is destroyed and becomes the initial value num = 0, and the variable is searched layer by layer from the inside to the outside of the function.

As mentioned earlier, when the function is executed, the local variables are destroyed, so why output 2?

The reference counting of garbage collection mechanism is involved here.

[about garbage collection] https://blog.csdn.net/zhouziyu2011/article/details/61201613

Brief description:

"when a variable is declared and a reference type value is assigned to it, the number of references to that value is 1; if the same value is assigned to another variable, the number of references to that value is increased by 1; if the variable that contains a reference to that value gets another value, the number of references to that value is subtracted by 1. When the number of references to the value becomes 0, the memory space it occupies can be reclaimed. The next time the garbage collector runs, the memory occupied by values with zero references will be freed. "

"answer"

When s () is executed for the first time, num = 1

When s () is executed for the second time, the variable num=1,num of the first s () is not destroyed when it is referenced, although 1 is added to the num=1.

"attention."

If the same reference is not used, then multiple calls have the same value, because no reference value is recorded.

After the function is executed, num = 1 is destroyed and the initial value is 0

❞var num = 1

Function getValue () {

Var num = 0

Return function () {

Num++

Console.log (num)

}

}

GetValue () ()

GetValue () ()

/ / 0 0

? The function of closure ❝

The attentive functions of closures are these two:

"you can read variables inside the function"but the value of the variable is always kept in memory" ❞Chestnut function f2 () {

Let num = 0

AddNum = function () {

Num++

}

Function f3 () {

Console.log (num)

}

Return f3

}

Var a = f2 ()

A ()

AddNum ()

A ()

/ / 0 1

The result is 0 1

When the function is finished, the local variables are destroyed. Shouldn't the result be 0 0?

In fact, a () is equivalent to the closure function of f3 (), which is executed twice.

The first time a () is executed, the result is 0, which is easy to understand. The second execution of the f2 () function inside the addNum function, found that no anonymous function assigned to a variable, and the variable did not add var / let, then its scope is global, saved in memory. When executing addNum, it accesses the local variable num inside the f2 () function. At this time, the existence of addNum depends on f2, so f2 is also in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends. The third time a () is executed, because the num is already in memory and the value is 1

Final output: 0,1

Closures note that because closures make all variables in the function stored in memory, memory consumption is very high, so closures should not be abused, otherwise it will cause performance problems of web pages and may lead to memory leaks in IE. The solution is to delete all unused local variables before exiting the function. The closure changes 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. ❞, after reading the above, have you mastered how to understand the JavaScript closure? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report