Created
May 20, 2013 21:34
-
-
Save curtis1000/5615763 to your computer and use it in GitHub Desktop.
An example of how closures work, and what makes them special
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
/** | |
* 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