I"m new to Javascript and programming in general and came upon this block of code from a book called Javascript Enlightenment (p.88):
var parentFunction = function() {
var foo = 'foo';
return function() { // anonymous function being returned
console.log(foo); // logs 'foo'
}
}
// nestedFunction refers to the nested function returned from parentFunction
var nestedFunction = parentFunction();
nestedFunction(); /* logs foo because the returned function accesses foo
via the scope chain */
Why does setting var nestedFunction = parentFunction();
enable nestedFunction();
to invoke the nested anonymous function and log "foo" to the console whereas using just parentFunction();
logs nothing at all?
Invoking parentFunction
returns the anonymous function without calling it.
nestedFunction
gets set as the return of parentFunction
, the anonymous function.
Invoking nestedFunction
hence invokes the anonymous function.
The anonymous function uses console.log
so you see "foo"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With