闭包,应用场景
- 模仿块级作用域
eg1:
for(var i=0;i<10;i++>){
(function(e){
console.log(e)
})(i)
}
eg2:
(function(){
var date=new Date()
})()
//外部不会访问到date
- 私有变量
eg0:
函数调用次数,奇数次打印0,偶数次打印1
function f(){
var num=0
function count(){
num++
if(num%2===0){
return 1
}else{
return 0
}
}
this.f2=function(){
return count()
}
}
let ff=new f()
console.log(ff.f2())//0
console.log(ff.f2())//1
console.log(ff.f2())//0
eg1:
function persion(name){
this.getName=function(){
return name
}
this.setName=function(val){
name=val
}
}
let per= new persion("jack")
per.getName()//jack
per.setName("rose")
per.getName()//rose
eg2:
function obj(){
var private=o
function privateCount(){
return private
}
this.publicMethod=function(){
private++
return privateCount()
}
}
-
节流防抖
-
函数柯里化
function add(){
var _arg=Array.prototype.slice.call(arguments)
var _result=function(){
_arg.push(...arguments)
return _result
}
_result.toString=function(){
return _arg.reduce(function(a,b){return a+b})
}
return _result
}
let r=add(1)(2)(3)
console.log(r)