What is Closures/Lambda in PHP or Javascript in layman terms? [duplicate]

筅森魡賤 提交于 2019-12-01 04:23:48

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)

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

JavaScript:

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

Anonymous functions are functions that are declared without a name.

For example (using jQuery):

$.each(array, function(i,v){
    alert(v);
});

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):

function alertNum(a){
    return function(){
        alert(a);
    }
}

The closure returns an anonymous function, but it does not have to be an anonymous function itself.

Continuing on the closure example:

alertOne = alertNum(1);
alertTwo = alertNum(2);

alertOne and alertTwo are functions that will alert 1 and 2 respectively when called.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!