functiona(){ functionb(){ var bb = 666 console.log(aa); //输出:333 } var aa = 333 return b } var demo = a() demo()
闭包的用途
1.封装私有变量
1 2 3 4 5 6 7 8 9 10 11 12
functionaddFn(){ let count = 1 functiona(){ count++ console.log(count); } return a } var acc = addFn() acc () //2 acc () //3 acc () //4
2.做缓存
函数一旦被执行完毕,其内存就会被销毁,而闭包的存在,就可以保有内部环境的作用域。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
functionfn1(){ var type ='JavaScript' let tt1 = 1 const tt2 = 2 var innerBar={ getType: function(){ console.log(tt1); return type }, setType:function(newType){ type = newType } } return innerBar } var bar = fn1() console.log(bar.getType()); //输出:1 JavaScript bar.setName('python') console.log(bar.setType()); //输出:1 python