闭包与匿名函数(区别?)

闭包与匿名函数(区别?)

问题描述:

可能的重复:
什么是 PHP 或 Javascript 中的闭包/Lambda外行术语?
闭包"和关闭"有什么区别拉姆达'?

我一直无法找到一个定义来清楚地解释闭包和匿名函数之间的区别.

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?

匿名函数就是没有名字的函数;而已.闭包是捕捉周围环境状态的函数.

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.

考虑这个假设的反例.考虑一种不支持闭包但支持匿名函数的语言 Foo.这种语言可能无法编译或为下面的代码抛出错误,因为问候"没有在内部函数的范围内定义.它是匿名的这一事实无关紧要.

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.

function outer() {
    var greeting = "hello ";

    (function(name) {
        alert(greeting + name);
    })("John Doe");
}

现在让我们考虑一种支持闭包的实际语言 - JavaScript.以上面相同的例子,但这次命名内部函数给出:

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:

function outer() {
    var greeting = "hello ";

    (function inner(name) {
        alert(greeting + name);
    })("John Doe");
}

虽然内部函数不再是匿名的,但它仍然从周围环境中捕获状态.

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.

function outer() {
    var greeting = "hello ";

    (function(name, greeting) {
        alert(greeting + name);
    })("John Doe", greeting);
}