1.匿名执行(直接执行),减少全局变量的污染.用于只执行一次的函数,比如初始化页面:
(function(){
alert("----1");
})()
2.缓存作用
var test=(function(){
var cache=[];
return {
test1:function(index){
cache.push(index);
alert(cache.length);
}
}
})();
for(var i=0;i<3;i++){
test.test1(i)
}
但是有一个缺点是,比较占用内存
3.封装
var test=(function(){
var name;
return {
getName:function(){
return name;
},
setName:function(n){
name=n;
}
}
})();
test.setName("xiang");
alert(test.name);//undefined
alert(test.getName());//xiang