What is Closures/Lambda in PHP or Javascript in la

2019-02-17 10:54发布

问题:

This question already has an answer here:

  • What is the difference between a 'closure' and a 'lambda'? 10 answers

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?

回答1:

SO already has the answers:

What is a lambda (function)?

How do JavaScript closures work?



回答2:

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


回答3:

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.



回答4:

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.