本文介绍了什么是Closures / Lambda在PHP或Javascript中的外行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中的Closures / Lambda是什么?一个例子将是伟大的,以帮助我的理解。我假设Lambda和Closures是一样的东西?

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?

推荐答案

lambda是一个匿名函数。闭包是一个带有它的范围的函数。我在这里的例子将在Python,但他们应该给你一个想法的适当的机制。

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.

print map(lambda x: x + 3, (1, 2, 3))

def makeadd(num):
  def add(val):
    return val + num
  return add

add3 = makeadd(3)
print add3(2)

map()调用中显示lambda, add3()是一个闭包。

A lambda is shown in the map() call, and add3() is a closure.

js> function(x){ return x + 3 } // lambda
function (x) {
    return x + 3;
}
js> makeadd = function(num) { return function(val){ return val + num } }
function (num) {
    return function (val) {return val + num;};
}
js> add3 = makeadd(3) // closure
function (val) {
    return val + num;
}
js> add3(2)
5

这篇关于什么是Closures / Lambda在PHP或Javascript中的外行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 05:31