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); }
Anurag Feb 06 2018-11-11T00: 00Z
source share