javascript-Closure of the understanding (easy to understand)

Source: Internet
Author: User
Tags closure variable scope

closures (closure) are a difficult and unique feature of the JavaScript language, and many advanced applications rely on closures.

the scope of a variable

to understand closures, you must first understand the special variable scope of JavaScript.

the scope of a variable is nothing more than two kinds: global variables and local variables.

the special point of the JavaScript language is that the global variables can be read directly inside the function.


JS Code

var n=999;

function F1 () {
alert (n);
}

F1 ();//999

on the other hand, a local variable inside a function cannot be read naturally outside the function.

JS Code

function F1 () {
var n=999;
}

alert (n);//Error

Here's a place to be aware that when declaring variables inside a function, be sure to use the var command. If not, you're actually declaring a global variable!

JS Code

function F1 () {
n=999;
}

F1 ();

alert (n);//999

--------------------------------------------------------------------------------------------------------

second, how to read the local variables from the outside?

for a variety of reasons, we sometimes need to get local variables within the function. However, as already mentioned, under normal circumstances, this can not be done, only through the workaround to achieve.

that is, in the inside of the function, define a function.

JS Code

function F1 () {

n=999;

function F2 () {
alert (n);//999
}

}

In the above code, the function F2 is included inside the function F1, and all local variables inside the F1 are visible to the F2. But the opposite is not possible, F2 internal variables, the F1 is not visible. This is the "chain-scoped" structure (chain scope) that is unique to the JavaScript language.

the child object looks up the variables for all the parent objects first-level. Therefore, all the variables of the parent object are visible to the child object, and vice versa.

since F2 can read the local variables in the F1, we can not read its internal variables outside the F1 as long as the F2 is the return value!


JS Code

function F1 () {

n=999;

function F2 () {
alert (n);
}

return F2;

}

var result=f1 ();

result ();///999

--------------------------------------------------------------------------------------------------------

Three, the concept of closure

the F2 function in the previous section of the code is the closure.

The definition of "closure" (closure) in various professional literature is very abstract and difficult to read. My understanding is that closures are functions that can read other functions ' internal variables.

because in the JavaScript language, only sub-functions inside the function can read local variables, it is possible to simply interpret the closure as "a function defined inside a function".

so, in essence, a closure is a bridge that connects the inside of the function to the outside of the function.

--------------------------------------------------------------------------------------------------------b

Iv. use of closures

closures can be used in many places. Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times.

How to understand this sentence? Take a look at the following code.


JS Code

function F1 () {

var n=999;

nadd=function () {n+=1}

function F2 () {
alert (n);
}

return F2;

}

var result=f1 ();

result ();///999

Nadd ();

result ();///

In This code, result is actually the closure F2 function. It runs altogether two times, the first value is 999, the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically cleared after the F1 call.

why is that? 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, and F2 's presence depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends.

Another notable part of this code is the line "nadd=function () {n+=1}", which first did not use the var keyword in front of Nadd, so Nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and this

The anonymous function itself is also a closure, so nadd is equivalent to a setter that can manipulate local variables inside the function outside of the function.

--------------------------------------------------------------------------------------------------------

v. Note points for using closures

1) Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may cause memory leaks. The workaround is to remove all unused local variables before exiting the function.

2) The closure changes the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, take the closure as its common method, and take the internal variable as its private property (private value), then be careful not to casually

change the value of the inner variable of the parent function.

--------------------------------------------------------------------------------------------------------

Liu, study questions

If you can understand the running result of the code below, you should understand the operation mechanism of the closure.

JS Code
var name = "The window";
var object = {
Name: "My Object",
getnamefunc:function () {
return function () {
return this.name;
};
}
};
alert (Object.getnamefunc () ());//the Window

--------------------------------------------------------------------------------------------------------
JavaScript Closures Example

function Outerfun ()
{
var a=0;
function Innerfun ()
{
a++;
alert (a);

}
Innerfun ()

The above code is wrong. The scope of Innerfun () is inside Outerfun () and it is wrong to call it outside the Outerfun ().

change to the following, i.e. closures:

JS Code

function Outerfun ()
{
var a=0;
function Innerfun ()
{
a++;
alert (a);
}
return innerfun;//Note here
}
var obj=outerfun ();
obj ();//result is 1
obj ();//result is 2
var obj2=outerfun ();
obj2 ();///result is 1
obj2 ();///result is 2

What is a closure package:

When an intrinsic function is referenced outside the scope that defines it, the inner function 's closure is created, and if the intrinsic function references a variable that is located outside the function, when the external function is called, the variables are not freed in memory because the closures require them.

--------------------------------------------------------------------------------------------------------

let's look at one more example

JS Code

function Outerfun ()
{
var a =0;
alert (a);
}
var a=4;
Outerfun ();
alert (a);

The result is 0,4. Because the var keyword is used inside a function to maintain the scope of a within outfun ().

then look at the following code:

JS Code

function Outerfun ()
{
//No var
a =0;
alert (a);
}
var a=4;
Outerfun ();
alert (a);
The result is 0, 0 is really strange, why?

A scope chain is a term that describes a path that can be used to determine the value of a variable. When a=0 is executed, because the VAR keyword is not used, the assignment is linked to Var a=4 along the scope and changes its value.




Vii. The garbage collection mechanism of JavaScript

in JavaScript, if an object is no longer referenced, the object is recycled by the GC. If two objects are referenced by each other and are no longer referenced by the 3rd, then the two mutually referenced objects are also recycled. Because function A is referenced by B and B is referenced by a c outside of a, this is why function A is not recycled after execution.

Viii. Conclusion

understanding JavaScript Closures is the way to advanced JS programmers, understanding their interpretation and operational mechanisms to write more secure and elegant code.

javascript-closure (easy to understand)

Related Article

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.