关闭与匿名函数(差异?) [英] Closure vs Anonymous function (difference?)

查看:116
本文介绍了关闭与匿名函数(差异?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复项:



'closure'和'lambda'之间的区别是什么?


Possible Duplicates:
What is Closures/Lambda in PHP or Javascript in layman terms?
What is the difference between a 'closure' and a '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。此语言可能无法编译或为下面的代码抛出错误,因为greeting未在内部函数的作用域中定义。

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);
}

这篇关于关闭与匿名函数(差异?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆