Home > Web Front-end > JS Tutorial > body text

A brief analysis of javascript closures and example analysis_javascript skills

WBOY
Release: 2016-05-16 18:13:25
Original
772 people have browsed it
Official explanation
"Closure" is an environment expression (usually a function) that has many variables and binds these variables, so these variables are also part of the environment expression.
Popular explanation
All functions in Javascript are closures. But generally speaking, the closure generated by nested functions is more powerful, which is what we call "closure" most of the time. Look at the following code:
Copy the code The code is as follows:



After executing var c=a() in this script, the variable c actually points to Function b is used, and variable i is used in b. After executing c(), a window will pop up to display the value of i. This code is actually a closure. Why? Because variable c outside function a refers to function b inside function a.
Garbage collection mechanism of Javascript
Due to the special garbage collection mechanism of JavaScript, closures are generated. The general rules of the Javascript garbage collection mechanism are as follows:
In JavaScript, if an object is no longer referenced, then the object will be recycled by the GC. If two objects refer to each other and are no longer referenced by a third party, then the two objects that refer to each other will also be recycled. In the above script, function a is referenced by b, and function b is referenced by c outside function a. This is why function a is not recycled after execution.
Application scenarios of closures
1. Protect variables within functions. Taking the above example as an example, variable i in function a can only be accessed by function b and cannot be accessed through other means, thus protecting the security of i.
2. Maintain a variable in memory. Still as in the above example, due to closure, i in function a always exists in memory, so every time c() is executed, i will be incremented by 1.
3. Implement JS private properties and private methods by protecting the security of variables (cannot be accessed externally). As follows, private properties and private methods are inaccessible outside the Constructor:
Copy code The code is as follows:

function Constructor(…){
var that = this;
var membername = value;
function membername(…){…}
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template