In javascript the definitive Guide 5th edition: the defining of closure:JavaScript functions are combination of code to executed and the scope in which to execute them.the combination of the code and scope is known as closure in the computer sicence literature.
however ,I don't know what is it? in my option, all functions in javascript are closure.but the "cloure" we usually say is certain function,just a example;
function NormalFun()
{
var i = 0 ;
function NestFun(){
alert( ++ i);
}
return NestFun;
}
var varFun = NormalFun(); // the varFun refers to the NestFun
varFun(); // print 1;
varFun(); // print 2
varFun(); // print 3
My defining of closure:there is a function that is called a nested function contained in another functiont we just call it father function ,when a variable out of the father function refers to the nested function,there will be a so-called "closure";
in other word,we defineda nested function in a father function body,but we use the nested function out of the father function.
in the above example,why the variable i lives all the time ,because the above program saves a reference to the nested function in the global scope.so the the garbage does not collecte;
to deeply understand the colsure,we need some conception:execution context,call object,scope,scope chain.
after above actions,what is the nestFunction's execution context?it is obvious,it is scope of the NormalFun;
when nestFunction is invoked,javascript interpreter does something as it does on NormalFun,so the sope chain includes three objects:its own call object,the call object of NormalFun,and the global object;
ok,let us explain why the GC does not work after the execution of NormalFun:
if we update the above code:
function NormalFun()
{
var i = 0 ;
function NestFun(){
i ++ ;
}
NestFun();
return i;
}
alert(NormalFun()); // 1
alert(NormalFun()); // 1
we don not return a function,there is nothing refers to the nestFun out of the NormalFun,so after the execuion of the NormalFun,the GC will work,so the updated program print 1 all the time;
when do we need the closure?
public class Class1
{
private string _test;
public string Test
{
get
{
return _test;
}
set
{
_test = value;
}
}
public Class1()
{
}
}
2.if we want to write a function that can remember a value across the invocation. we need a colsure.(we can also use a global variable,but which can pollute the global namepaces).in the case,it likes the static variable in C#
public class Class1
{
private static int i = 0 ;
public static int ReturnI()
{
return ++ i;
}
public Class1()
{
}
}
because of the closure,some objects are in the memory all the time,so closure can waste memory,so we should take care of it when we use a closure,maybe a memory leak does;
deeply understanding closure is important for a web developer,it is a must if you want to be a advanced javascript programmer,however,I don't think i have understood it well,i need more thinking.