Last active
August 29, 2015 14:06
-
-
Save 67hz/08da59f1ede0bcf69c75 to your computer and use it in GitHub Desktop.
Closure demystified. Closure is best expressed when a function returns an anonymous function. If the nested anonymous function references a variable within the parent function context, that variable reference will be accessible when the nested function is invoked.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var multiplyByNumber = function (x) { | |
return function(y) { | |
// this nested anonymous function references | |
// parent 'x' arg variable | |
return x * y; | |
} | |
} | |
/** | |
* multiplyBy5 below is a function because multiplyByNumber returns a function. | |
* To reiterate, the below statement is the equivalent of | |
* var multiplyBy5 = function(y) { | |
* return 5 * y; | |
* } | |
*/ | |
var multiplyBy5 = multiplyByNumber(5); | |
var multiply10x5 = multiplyBy5(10); | |
console.log(multiply10x5); // logs 50 | |
/** | |
* So we see closure in action. multiplyBy5 points to the nested anonymous | |
* return function within multiplyByNumber and | |
* that nested function was initially given an 'x' value of 5 on line 16. | |
* This accessible 'x' value from the multipylyByNumber function context is available | |
* because of closure. When this child function is invoked it still | |
* has access to the parent's function scope. | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment