Short answer:
The closure created by the callback in the second example, will look for the global variable something
which does not exist.
Vs. the first example creates a closure around the variable something
within function a
. If the value of something
is mutated, calling a
again will produce a different value.
Consider the following different ways to pass callback functions:
var something = "Global something";
function a(callback) {
var something = "Local something";
callback(something);
}
a( console.log ); // "Local something"
As defined, console.log()
will accept the something
passed by function a
as its first argument and prints it out to the screen. Closure happens on the local variable.
a( function() {console.log(something)} ); //"Global something"
When you define a function inline it creates its own scope, and references a local variable something
.
The something
passed by function a
gets dropped as the inline function did not catch it.
In some stricter languages it will throw an error, but JS does not.
The inline function tries to console.log
the local variable something
, which is not found. Searches global scope and finds "Global something" and prints it. No closure on the local variable.
a( function(x) {console.log(x)} ); //"Local something"
The inline function creates and references local variable x
.
But x
points to the something
variable passed by function a
, which in turn which points to "Local something", which gets printed. Closure on the local variable.