Skip to content

Instantly share code, notes, and snippets.

@curtis1000
Created May 20, 2013 21:34
Show Gist options
  • Save curtis1000/5615763 to your computer and use it in GitHub Desktop.
Save curtis1000/5615763 to your computer and use it in GitHub Desktop.
An example of how closures work, and what makes them special
/**
* We are not assigning a function to myObject, only the result of
* invoking a function. While the returned object (which is assigned
* to "myObject") contains methods that can access the "value" variable,
* the "value" variable cannot be accessed directly through "myObject".
* This is how closures achieve information hiding, a.k.a. private variables.
*
* Information hiding is useful when we want to provide users with an interface,
* and prevent users from tampering with the javascript objects in ways that we
* do not want them to (hacking with private vars).
*/
var myObject = (function () {
var value = 0;
return {
increment: function (inc) {
value += typeof inc === 'number' ? inc : 1;
},
getValue: function () {
return value;
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment