Created
March 30, 2015 07:14
-
-
Save ddeveloperr/210d996ae81f8e6933be to your computer and use it in GitHub Desktop.
Closure in JS examples
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
// | |
function wrapValue(n) { | |
var localVariable = n; | |
return function() { return localVariable; }; | |
} | |
var wrap1 = wrapValue(1); | |
var wrap2 = wrapValue(2); | |
console.log(wrap1()); | |
// → 1 | |
console.log(wrap2()); | |
// → 2 | |
// Example 2 | |
function makeAdder(x) { | |
return function(y) { | |
return x + y; | |
}; | |
} | |
var add5 = makeAdder(5); | |
var add10 = makeAdder(10); | |
console.log(add5(2)); // 7 | |
console.log(add10(2)); // 12 | |
// More examples : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment