Closing versus anonymous function (difference?)

Possible duplicates:
What is Closures / Lambda in PHP or Javascript in layman's terms?
What is the difference between closing and lambda?

Hello,

I could not find a definition that clearly explains the differences between closure and anonymous function.

Most of the links I've seen clearly state that they are β€œthings,” but I can't understand why.

Can anyone simplify it for me? What are the specific differences between these two language features? Which one is more suitable for which scenarios?

+49
closures anonymous-function
Feb 06 2018-11-11T00:
source share
1 answer

An anonymous function is simply a function that does not have a name; nothing more. Closing is a function that captures the state of the environment.

An anonymous function does not have to create a closure, and a closure is not created only for anonymous functions.

Consider this hypothetical counterexample. Consider the Foo language, which does not support closure, but supports anonymous functions. This language may either fail to compile or produce an error for the code below, because the "greeting" is not defined in the scope of the internal function. The fact that he is anonymous does not matter.

function outer() { var greeting = "hello "; (function(name) { alert(greeting + name); })("John Doe"); } 

Now let's look at the actual language that supports closure - JavaScript. Taking the same example as above, but let's call the inner function this time:

 function outer() { var greeting = "hello "; (function inner(name) { alert(greeting + name); })("John Doe"); } 

Although the internal function is no longer anonymous, it still captures the state from the environment.

Closing provides much-needed convenience, because otherwise we will pass each dependency to the function as an argument.

 function outer() { var greeting = "hello "; (function(name, greeting) { alert(greeting + name); })("John Doe", greeting); } 
+70
Feb 06 2018-11-11T00:
source share



All Articles