第一点:什么是闭包 一个函数内嵌套一个子函数,子函数可以访问父函数 (官方解释:一个函数调用另一个函数的局部变量) 闭包就是一个内部函数,它实在另一个函数内部的函数 eg:0 function outer(){ function inner(){
}
} 这就是闭包; eg: function fn(){ const a=3; function fn2(){ a++; return a } return fn2() } const closeureFn=fn(); console.log(closeureFn)
eg2: const people=[ { firstname:"aaFirstname", lasstname:'ccFirstname', },{ firstname:'bbFirstname', lasstname:"ffFirstname" }]
const sortBy=(pro)=>{
return (a,b)=>{
return (a[pro]<b[pro]? 1:(a[pro]>b[pro]?1:0))
}
}
const resultPro=people.sort(sortBy('firstname'));
console.log(resultPro)
eg3:function wait(message){ setTimeout(()=>{ console.log(message) },1000) } wait('hello') 举例说明: 闭包无处不在,比如:定时器,事件监听器,Ajax请求,跨窗口通信,web Workers ,只要使用了回调,实际上就是使用闭包 闭包和模块的结合使用 function CoolMule(){ const something='cool'; const another=[1,2,3]; function doSomething(){ console.log(something); } function doAnother(){ console.log(another.join("!"))
}
return {
doSomething:doSomething,
doAnother:doAnother
}
}
const foo=CoolModule();
foo.doSomething();
foo.doAnother();