Last active
January 16, 2018 17:03
-
-
Save jayjariwala/95ac08b3eccea08b06c6063fb7096f08 to your computer and use it in GitHub Desktop.
Closure Example
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
You can think of clousre as a way of "remember" and continue to access a function's scope even once the function has finished running. | |
function makeAddr(x) | |
{ | |
//paraneter 'x' is an inner variable | |
//inner function add() uses 'x', so it has clousre over it | |
function add(y) | |
{ | |
return x + y; | |
} | |
return add; | |
} | |
var plusOne = makeAddr(1); | |
plusOne(10); // it will return 11 as it remembers the value of outerscope x | |
var plusTen = makeAddr(10); | |
plusTen(10); // it will return 20 as it remembers the value of outerscope which is 10; | |
steps on how code works | |
1) when we call makeAddr(1), we get back a rederence to its inner add(...) that remembers x as 1. | |
we call this function reference plusOne(...). | |
2) when we call plusOne(3), it adds 3(its inner y)to the 1(remembered by x), and we get 4 as the result.' | |
Modules | |
// the most common usage of closure in Javascript is the module pattern. | |
// modules let you define private implementation details (variables, function) that are hidden from the outside world, as well as a public API that is accesible from the outside. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment