关于函数闭包、函数作为参数传递疑问

1.描述:

我想得到一个函数数组 result ,首先func函数向数组result里添加匿名函数(每个匿名函数都保存了各自的num)

但是我将return 后面的匿名函数我用参数传进来,相当于只是做了替换而已,为什么结果却不同呢。

https://img3.mukewang.com/5c233ec10001509003770260.jpg

下面我将 return 后面匿名函数作为参数传进去就获取不到。

https://img1.mukewang.com/5c233ec90001356503140285.jpg

largeQ
浏览 578回答 1
1回答

绝地无双

因为第二段代码中的fn是定义在全局环境中的。你可以看看这里和下边的代码,希望对你有帮助function func(fn){&nbsp; var result =[] ;&nbsp; for(var i=0;i<3;i++){&nbsp; &nbsp; result.push(&nbsp; &nbsp; &nbsp; function (num){&nbsp; &nbsp; &nbsp; &nbsp; return fn;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; }(i)&nbsp; &nbsp; );&nbsp; }&nbsp;return result;}function fn(){&nbsp; return num;}var num = 1;console.log(func(fn)[1]()); //1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript