var myObject=function(){
var value=0;
return {
increment: function(inc){
value +=inc;//不能加this,this指向全局对象
},
getValue: function(){
return value;
}
}
}();
myObject.increment(2);
console.log(myObject.getValue());
什么是闭包?
Closures are functions that refer to independent (free) variables.
In other words, the function defined in the closure 'remembers' the environment in which it was created.
闭包有什么用?
如本文所展示的例子:
借助javascprit的链式作用域实现对私有变量的封装,并使其常驻内存
另外《学习Javascript闭包(Closure)》举的例子也很好
例1:
function f1(){
var n=999;
nAdd=function(){n+=1}
function f2(){
alert(n);
}
return f2;
}
var result=f1();
result(); // 999
nAdd();
result(); // 1000
例2:
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()());
例3:
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
var that = this;
return function(){
return that.name;
};
}
};
alert(object.getNameFunc()());