Created
May 19, 2015 23:33
-
-
Save mde/8c5c8a3cd48d6c2dd545 to your computer and use it in GitHub Desktop.
JavaScript closures
This file contains hidden or 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 foo = function (seed) { | |
var currVal = seed; | |
var incrementor = function () { | |
currVal++; | |
console.log(currVal); | |
}; | |
return incrementor; | |
}; | |
var bar = foo(3); | |
bar(); // Logs 4 | |
bar(); // Logs 5 | |
bar(); // Logs 6 | |
var baz = function (seed) { | |
var firstFactor = seed; | |
var multiplier = function (secondFactor) { | |
console.log(firstFactor * secondFactor); | |
}; | |
return multiplier; | |
}; | |
var qux = baz(3); | |
qux(4); // Logs 12 | |
qux(7); // Logs 21 | |
qux(10); // Logs 30 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment