Created
January 17, 2014 21:10
-
-
Save lazd/8481583 to your computer and use it in GitHub Desktop.
Private variables in ES5. Technique adapted from http://fitzgeraldnick.com/weblog/53/
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
| var SomeClass = (function() { | |
| // We'll store in an object to be as light as possible | |
| var privates = {}; | |
| // Each instance will get its own ID | |
| var nextId = 0; | |
| function SomeClass() { | |
| // Store a non-writable property called _ | |
| // This will contain our instance's ID | |
| Object.defineProperty(this, '_', { | |
| value: nextId++, | |
| writable: false | |
| }); | |
| privates[this._] = { | |
| // Private stuff here | |
| privateString: 'This string is private!' | |
| }; | |
| } | |
| SomeClass.prototype.destruct = function() { | |
| // Cleanup after ourselves | |
| delete privates[this._]; | |
| }; | |
| SomeClass.prototype.someMethod = function() { | |
| // Get a private variable | |
| var privateString = privates[this._].privateString; | |
| console.log(privateString); | |
| }; | |
| return SomeClass; | |
| }()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment