A brief analysis of Javascript closures (i.)

Source: Internet
Author: User

Closed Package

For JavaScript programmers, closures (closure) are a hard-to-understand and must-conquer concept. The formation of closures is closely related to the life cycle of variables.

Scope of the variable
The scope of the variable, which refers to the valid range of the variable. What we most often talk about is the scope of the variables declared in the function.
When declaring a variable in a function, if the variable is not preceded with a key in Var, the variable becomes a global variable, which is, of course, an easy way to create a naming conflict. (ES5 strict mode error)
Another case is to declare the variable in the function with the Var keyword, when the variable is both a local variable and only within the function to access the variable, which is not accessible outside the function.
In JavaScript, functions can be used to create function scopes, and inside functions you can see variables outside of the function, but not inside functions. Because when you search for a variable in a function, if the variable is not declared within the function, the search process will search for the global object as the scope chain created by the code execution Environment is searched for the outer layer. The search for variables is from inside to outside and not from outside to inside.

Cases:
var a = 1
var func1 = function () {
var B = 1
var func2 = function () {
var c = 3
Console.log (b)//1
Console.log (a)//1
}
Func2 ()
Console.log (c)//output: uncaught referenceerror:c is not defined
}
Func1 ()

Declaration period of a variable
In addition to the scope of the variable, another concept related to closures is the life cycle of the variable.
For global variables, the lifetime of a global variable is, of course, permanent, unless we actively destroy the global variable.
For local variables declared with the VAR keyword within a function, when exiting a function, these local variables lose the value of the gate, and they are destroyed as the function call ends.

Cases:
var func = function () {
var a = 1; Local variable A will be destroyed after exiting function
Console.log (a)
}
Func ()

Now look at this code.
var func = function () {
var a = 1
return function () {
a++
Console.log (a)
}
}
var f = func ()

F ()//2
F ()//3
F ()//4
F ()//5

When the function is exited, the variable A is not destroyed, but is still alive somewhere. This is because when you execute var f = func (), F returns a reference to an anonymous function that can access the environment that is generated when the Func () is called, and local variable A is in this environment. Since the environment in which local variables are located can also be accessed by outsiders, this local variable has the reason for not being destroyed. This creates a closure structure where the life of the local variable appears to be continued

Closure Classic Example:
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>

<script>
var nodes = document.getelementsbytagname (' div ')

for (var i = 0, len = nodes.length; i < Len; i++) {
Nodes[i].onclick = function () {
Console.log (i)
}
}
</script>

This code regardless of click that div result is 5, this is because the onclick event of the div node is triggered asynchronously, when the event is triggered, the for loop has already ended, at this time the value of I is already 5, when the OnClick event function in the scope chain from inside to outside to look for the variable i, Find always 5

Solution:
for (var i = 0, len = nodes.length; i < Len; i++) {
(function (i) {
Nodes[i].onclick = function () {
Console.log (i)
}
}) (i)
}

Practical application:
var Type = {}

for (var i = 0, type; type = [' String ', ' Array ', ' number '][i++];) {
(function (type) {
Type[' is ' + type] = function (obj) {
return Object.prototype.toString.call (obj) = = = ' [Object ' + type + '] '
}
}) (Type)
}

Type.isarray ([])//True
type.isstring (' str ')//True

A brief analysis of Javascript closures (i.)

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.