Skip to content

Instantly share code, notes, and snippets.

@edysegura
Last active September 16, 2015 23:06
Show Gist options
  • Save edysegura/33eb5780817a2daa15e5 to your computer and use it in GitHub Desktop.
Save edysegura/33eb5780817a2daa15e5 to your computer and use it in GitHub Desktop.
[JS] A closure example in JavaScript to hold the context
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