JavaScript closure

a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function.

http://en.wikipedia.org/wiki/Closure_(computer_science)

Notes:

  1. The initial values of the non-local variables depends on not where the closure define,but where the closure call.
  2. Referencing environment ,not copy.Meaning when you call a variable references to a closure twice,the environment maybe change.
  3. Every time you hold a returened closure using a varible will initialize it's referencing enviroment.

Example:

var name="Window";
var Top={
    name:"top",
    Inner:{
        name:"inner",
        getName:function(){
            var that=this;
            var i=0;//note1
            function increase(){
                var rt="this binding:"+this.name+"\\n\\n"+"number i:"+i;//this binding
                i++;
                return rt;
            };
            i++;//note1
            return increase;
        }
    }
};
var closure1=Top.Inner.getName();
alert("first call closure1"+"\\n"+closure1());//note1
var closure2=Top.Inner.getName();
alert("first call closure2"+"\\n"+closure2()); //note1,note3
alert("againe call closure1"+"\\n"+closure1());//note2
alert("againe call closure2"+"\\n"+closure2());//note2
var closure21=closure2;
alert("first call closure21"+"\\n"+closure3());//assign another varible has referencing enviroment
References ----------

Comments