Learn to summarize JavaScript closures

Source: Internet
Author: User
Tags closure

Study Address: Http://stackoverflow.com/questions/111102/how-do-javascript-closures-work

1, a simple implementation of closures
Example 1
function SayHello (name) {
var words = "Hello," + name;


var sayforalert = function () {
alert (words);
}


Sayforalert ();
}
SayHello ("Jack");
/*


An Example of a Closure


Sentence summaries:


A closure is the local variables for a function-kept alive after the function has returned, or
A closure is a stack-frame which was not deallocated when the function returns (as if a ' stack-frame ' were malloc ' Ed Instea D of being on the stack!).
*/




function SayHello2 (name) {
var words = "Hello," +name; local variables;
var sayforalert = function () {
alert (words);
}

return sayforalert;
}


var say2 = SayHello2 ("Lucy");
Say2 ();


/*
A reference to a function. Return as a parameter.

This is the equivalent of returning a function
Pointer.

Sayforalert and Say2 point to the same function.


An important difference between Javascrip and C is that the C pointer points to a function, and JavaScript is a reference to a function.

(equivalent to a hidden pointer).


In many languages, it is the same as C. When the function is finished, local variables cannot be visited again.
Because the stack of its functions is destroyed.


In JavaScript, functions can be declared inside the function. And local variables can be interviewed and
It is returned in the declared function.


*/



function Saynumadd () {
var num = 666;

var showalert = function () {
alert (num);
Num++;//place 2;
}
Num++;//place 1;
return showalert;
}


var saynumber = Saynumadd ();
Saynumber ();//alert 667;
/*
Note: According to the above results, NUM is saved as a variable in the back.
The call to the function can be retrieved again.

Suppose we put the num++ in the Place2 position.
The result is 666. Description function Run sequence run Saynumadd () run process
In 1. Declare the variable num,2, declare the function showalert,3, and add the variable num from 1.
When we run Saynumber (), we see the result that 667 is saved after it is added.


*/
function Setupsomeglobals () {
var num = 666;

Store some references to function as global variables
Getalertnumber = function () {
alert (num);
}

Getincreasenumber = function () {
num + +;
}
Getsetnumber = function (x) {
num = x;
}
}


Setupsomeglobals ();
Getincreasenumber ();
Getalertnumber ();
Getsetnumber (10);
Getalertnumber ();//10


Setupsomeglobals ();
Getalertnumber ();//666
/*
Onte:
As can be seen from the examples above,
The three functions inside the setupsomeglobals are declared to have access to the variables inside.




Suppose we call Setupsomeglobals again () A new function stack is created. Previously created by Getalertnumber, Getincreasenumber, Getsetnumber will be rewritten and have a new closure. (in JavaScript, it is possible to declare another function inside a function, regardless of what is in it, when the outside function is invoked.) The function inside will be created again.)
*/


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,4]);
for (var j=0; J < Fnlist.length; J + +) {
FNLIST[J] ();
}
}


Testlist ();//alert item1 undefined;
/*
Execution results. It can be explained that function inside function can only save local variables, cannot save parameter variables. Therefore, we should pay attention to the scope of variables in the use of the packet function.
*/


function Calllocalvar () {
var sayalertname = function () {alert (name)};
var name = "Jacy";

return sayalertname;
}
Calllocalvar () ();//Such a write will first run Calllocalvar and then run the returned Sayalertname;


/*
Note
Summary closure functions are able to access variables defined by the same domain, whether in front of or behind the closure function. Only if the same domain can be interviewed.
*/


function Checkclosure (Somenum, Someref) {

var num = somenum;
var arr = [n/a];
var ref = Someref;

return function (x) {
num + = x;
Arr.push (num);
Alert (' num: ' +num + ' \ n arr: ' +arr.tostring ()
+ ' \ n ref.somevar ' +ref.somevar);
}
}


var obj = {Somevar:4};
var fn1 = checkclosure (4,obj);
var fn2 = checkclosure (5,obj);


FN1 (1);//Num:5; arr:1,2,3,5; Ref.somevar:4;
FN2 (1);//Num:6; arr:1,2,3,6; Ref.somevar:4;


Obj.somevar + +;


FN1 (2);//Num:7; arr:1,2,3,5,7; Ref.somevar:5;
FN2 (2);//num:8; arr:1,2,3,6,8; Ref.somevar:5;


/*
Note
The writing here overcomes the problem that the argument cannot be saved, just to create a local scope a variable to receive the value of the parameter variable can be.


Be able to describe different scopes and not affect each other.


*/

Learn to summarize JavaScript closures

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.