用外行人的话来说,PHP 或 Javascript 中的 Closures/Lambda 是什么?
通俗地说,PHP 或 JavaScript 中的闭包/Lambda 是什么?一个例子非常有助于我的理解。我假设 Lambda 和闭包是同一件事?
What are Closures/Lambda in PHP or JavaScript in layman terms? An Example would be great to aid my understanding. I am assumning Lambda and Closures are the same thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
SO 已经有了答案:
什么是 lambda(函数)?
JavaScript 闭包如何工作?
SO already has the answers:
What is a lambda (function)?
How do JavaScript closures work?
lambda 是一个匿名函数。闭包是一个带有其作用域的函数。我这里的示例将使用 Python,但它们应该能让您了解适当的机制。
lambda 在
map()
调用中显示,而add3()
是一个闭包。JavaScript:
A lambda is an anonymous function. A closure is a function that carries its scope with it. My examples here will be in Python, but they should give you an idea of the appropriate mechanisms.
A lambda is shown in the
map()
call, andadd3()
is a closure.JavaScript:
匿名函数是没有名称声明的函数。
例如(使用 jQuery):
这里的函数是匿名的,它是专门为这个
$.each
调用而创建的。闭包是一种函数类型(它可以在匿名函数中使用,也可以被命名),其中传递给它的参数被“捕获”,并且即使在范围之外也保持不变。
闭包(在 JavaScript 中):
闭包返回一个匿名函数,但它本身不必是匿名函数。
继续闭包示例:
alertOne
和alertTwo
是在调用时分别发出警报 1 和 2 的函数。Anonymous functions are functions that are declared without a name.
For example (using jQuery):
The function here is anonymous, it is created just for this
$.each
call.A closure is a type of function (it can be used in an anonymous function, or it can be named), where the parameters passed into it are 'captured' and stay the same even out of scope.
A closure (in JavaScript):
The closure returns an anonymous function, but it does not have to be an anonymous function itself.
Continuing on the closure example:
alertOne
andalertTwo
are functions that will alert 1 and 2 respectively when called.匿名函数,也称为闭包,允许创建没有指定名称的函数。它们作为回调参数的值最有用,但它们还有许多其他用途。 Lambda 函数允许快速定义不在其他地方使用的一次性函数。
Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Lambda functions allow the quick definition of throw-away functions that are not used elsewhere.