企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] >[success] # 闭包的理解 ~~~ 想实现每次调用方法时'num'都' +1',正常想法是用一个全局变量来实现。 ~~~ <br/> >[success] ## 全局变量实现 ~~~ let num = 1 function test(){ console.log(++num) } test() // 2 test() // 3 ~~~ <br/> >[success] ## 闭包的实现 ~~~ function test(){ let num = 1 return function (){ console.log(++num) } } let test1 = test() // 这里执行了一遍test() // 下面的test1()实际上是执行了test方法里面return的方法 test1() // 2 test1() // 3 ~~~ <br/> >[success] ## 闭包的自执行函数写法 ~~~ let test = (function(){ let num = 1 return function (){ console.log(++num) } })() test() test() // 自执行函数写法 (function(){})() ~~~