In JavaScript, what is a closure (Closure)

Source: Internet
Author: User
Tags anonymous closure functions variables reference return tostring
Two features of JavaScript closures:

1, as a reference to a function variable-when the function returns, it is active.
2. A closure is when a function returns, a stack area without releasing resources.

Example 1. <script type= "Text/javascript" >
function SayHello2 (name) {
var text = ' Hello ' + name; Local variable
var sayalert = function () {alert (text);}
return sayalert;
}
var sy = SayHello2 (' Never-online ');
Sy ();
</script>
As a JavaScript programmer, it should be understood that the above code is a reference to a function. If you do not understand or are not clear, please first understand some basic knowledge, I do not describe here.

What is the above code for a closure?
Because there is an embedded anonymous function in the SayHello2 function
Sayalert = function () {alert (text);}
in JavaScript. If you create an inline function (as in the previous example), you create a closure.

In the C or other mainstream language, when a function returns, all local variables are inaccessible because their stack has been destroyed. But in JavaScript, if you declare an inline function, the local variable will still be accessible after the function returns. For example, the variable sy in the above example refers to an anonymous function function () {alert (text) in an inline function, which can be changed to this: <script type= "Text/javascript" >
function SayHello2 (name) {
var text = ' Hello ' + name; Local variable
var sayalert = function () {alert (text);}
return sayalert;
}
var sy = SayHello2 (' Never-online ');
Alert (sy.tostring ());
</script> This is also consistent with the second feature of closures.

Example 2. <script type= "Text/javascript" >
function say667 () {
Local variable which ends up within closure
var num = 666;
var sayalert = function () {alert (num);}
num++;
return sayalert;
}

var sy = say667 ();
Sy ();
Alert (sy.tostring ());
</script>
In the code above, the anonymous variable function () {alert (num);} The num in is not copied, but continues to refer to the value in the local variable--num defined by the outer function until the outer function say667 () returns.

Example 3. <script type= "Text/javascript" >
function Setupsomeglobals () {
Local variable which ends up within closure
var num = 666;
Store some references to functions as global variables
Galertnumber = function () {alert (num);}
Gincreasenumber = function () {num++;}
Gsetnumber = function (x) {num = x;}
}

</script>
<button > Generation-setupsomeglobals () </button>
<button > Output value-galertnumber () </button>
<button > Add-gincreasenumber () </button>
<button > Assignment 5-gsetnumber (5) </button>
In the example above, Galertnumber, Gincreasenumber, Gsetnumber are all references to the same closure, Setupsomeglobals (), because they declare--setupsomeglobals () through the same global invocation.
You can view the output by "generate", "Add", "assign", "Output value" three buttons. If you click the "Build" button, a new closure will be created. The three functions of Galertnumber (), Gincreasenumber (), Gsetnumber (5) are rewritten.

If you understand the above code, look at the following example:

Example 4. <script type= "Text/javascript" >
function buildlist (list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = ' Item ' + list[i];
Result.push (function () {alert (item + ' + List[i])});
}
return result;
}

function Testlist () {
var fnlist = buildlist ([1,2,3]);
Using J-to-help prevent confusion-could use I
for (var j = 0; J < Fnlist.length; J + +) {
FNLIST[J] ();
}
}

Testlist ();
</script>
Run Result:
Item 3 is undefined
Item 3 is undefined
Item 3 is undefined

Code Result.push (function () {alert (item + ' + List[i])}),
The result array was added with a reference to three anonymous functions. This code can also be written as
var p = function () {alert (item + ' + List[i])};
Result.push (P);

about why output three times are "Item 3 is undefined"

It has been explained in the example say667 () above.
The list[i in the anonymous function function () {alert (item + ' + list[i])} ' is not a copy, but a reference to the parameter list. Until the function buildlist () returns, that is, the last reference is returned. That is, traversing the list (note: List of the largest subscript should be 2), after i++ also became 3, which is why the item 3, and LIST[3] itself is not initialized, nature is undefined.

Example 5. <script type= "Text/javascript" >
function Newclosure (Somenum, Someref) {
Local variables this end up within closure
var num = somenum;
var anarray = [1,2,3];
var ref = Someref;
return function (x) {
num = x;
Anarray.push (num);
Alert (' num: ' + num +
' \nanarray ' + anarray.tostring () +
' \nref.somevar ' + Ref.somevar);
}
}
var closure1 = newclosure ({somevar: ' Never-online '})
var closure2 = newclosure ({somevar: ' Bluedestiny '})
Closure1 (4)
Closure2 (3)
</script>


In this last example, show how to declare two different closures.



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.