JS中闭包的作用

1、执行自执行函数。某些函数可能只需要执行一次而且为了不造成全局污染。声明变量需要使用var,否则会默认添加到全局对象的属性上。或者别的函数可能会误用该属性。全局对象过于庞大的话,会影响访问速度。(变量的取值需要从原型链上遍历)

(function(value){
console.log(value)
})(3);

2、作为缓存.第二次使用对象时候,可以不用新建对象。单例模式的实现等等。

var Cache=(function(){
var cache={};
return{
getObj:function(name){
if(name in cache){
return cache[name];
}
var temp=new Object(name);
cache[name]=temp;
return temp;
}
}
})()

3、实现封装过程。封装对象中的变量不能直接访问,提过提供的闭包来访问。

var person=function(){
var name="no name!";
return {
getName:function(){
return this.name;
},
setName:function(value){
this.name=value;
}
}
}()

4、实现面向对象

总结:闭包就是别的函数中返回出来的函数,这个函数可以访问返回该函数的函数中内部的变量!

猜你喜欢

转载自www.cnblogs.com/anthong0325/p/9297401.html
今日推荐