Skip to content

Instantly share code, notes, and snippets.

@nulayuhz
Created December 9, 2014 22:29
Show Gist options
  • Save nulayuhz/f28d60b76f986c55392e to your computer and use it in GitHub Desktop.
Save nulayuhz/f28d60b76f986c55392e to your computer and use it in GitHub Desktop.
closure cont'
function foo() {
var a = 2;
function bar() {
console.log( a );
}
return bar;
}
var baz = foo();
baz();
bar() has lexical scope access to inner scope of foo().
after we execute foo(), we assign the value it returned to baz, then we actually invoke baz(),
which invoke our inner function bar(). bar is executed outside of its declared lexical scope.
---
After foo() executed, normally we would expect that the entirety of the inner scope of foo() would go away, because we know that the Engine employs a Garbage Collector that frees up memory once it's no longer in use.
But the 'magic' of closures does not let this happen. That inner scope is in fact still 'in use' by bar(), and thus does not go away.
By virtue of where it was declared, bar() has lexical scope closure over that inner scope of foo(), which keeps that scope alive for bar() to reference at any later time.
*** bar() still has a reference to that scope, and that reference is called closure. ***
The function is being invoked well outside of its author-time lexical scope. Closure lets the function continue to access the lexical scope it was defined in at author-time.
***Any of the various ways that functions can be passed around as values, and indeed invoked in other locations, are all examples of observing/exercising closure ***
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment