Last active
September 16, 2015 23:06
-
-
Save edysegura/33eb5780817a2daa15e5 to your computer and use it in GitHub Desktop.
[JS] A closure example in JavaScript to hold the context
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
function myClosure(name) { | |
var x = 0; | |
//private method | |
function doCount() { | |
console.log("Count " + name + ", count: " + x++); | |
} | |
//public | |
return { | |
count: doCount | |
}; | |
}; | |
var c1 = myClosure("Dependency 1"); | |
c1.count(); //Count Closure 1, count: 0 | |
c1.count(); //Count Closure 1, count: 1 | |
c1.count(); //Count Closure 1, count: 2 | |
c1.count(); //Count Closure 1, count: 3 | |
var c2 = myClosure("Dependency 2"); | |
c2.count(); //Count Closure 2, count: 0 | |
c2.count(); //Count Closure 2, count: 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment