闭包与匿名函数(区别?)
可能的重复:
什么是 PHP 或 Javascript 中的 Closures/Lambda外行术语?
“闭包”和“闭包”之间有什么区别拉姆达'?
嗨,
我一直找不到一个定义来清楚地解释闭包和匿名函数之间的区别。
我见过的大多数参考文献都明确指出它们是不同的“事物”,但我似乎无法理解为什么。
有人可以帮我简化一下吗?这两种语言特性之间有什么具体区别?哪一种更适合什么场景?
Possible Duplicates:
What is Closures/Lambda in PHP or Javascript in layman terms?
What is the difference between a 'closure' and a 'lambda'?
Hi,
I have been unable to find a definition that clearly explains the differences between a closure and an anonymous function.
Most references I have seen clearly specify that they are distinct "things" yet I can't seem to get my head around why.
Could someone please simplify it for me? What are the specific differences between these two language features? Which one is more appropriate in what scenarios?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
匿名函数只是一个没有名称的函数;而已。闭包是捕获周围环境状态的函数。
匿名函数不一定需要创建闭包,并且闭包也不是仅为匿名函数创建的。
考虑这个假设的反例。考虑一种不支持闭包但支持匿名函数的语言 Foo。该语言可能无法编译以下代码或引发错误,因为“greeting”未在内部函数的范围内定义。它是匿名的这一事实是无关紧要的。
现在让我们考虑一种支持闭包的实际语言——JavaScript。与上面的例子相同,但这次命名内部函数给出:
尽管内部函数不再是匿名的,但它仍然从周围环境捕获状态。
闭包提供了非常需要的便利,否则我们将把函数的每个依赖项作为参数传递。
An anonymous function is just a function that has no name; nothing more. A closure is a function that captures the state of the surrounding environment.
An anonymous function does not necessarily need to create a closure, and a closure is not created only for anonymous functions.
Consider this hypothetical counter-example. Consider a language Foo which does not support closures but supports anonymous functions. This language may either not compile or throw an error for the code below because "greeting" is not defined in the scope of the inner function. The fact that it is anonymous is irrelevant.
Let's consider an actual language now that does support closures - JavaScript. Taking the same example as above, but naming the inner function this time gives:
Although the inner function is not anonymous anymore, it still captures state from the surrounding environment.
Closures provide much needed convenience, as otherwise we would be passing every single dependency of the function as an argument.