Skip to content

Instantly share code, notes, and snippets.

@lazd
Created January 17, 2014 21:10
Show Gist options
  • Select an option

  • Save lazd/8481583 to your computer and use it in GitHub Desktop.

Select an option

Save lazd/8481583 to your computer and use it in GitHub Desktop.
Private variables in ES5. Technique adapted from http://fitzgeraldnick.com/weblog/53/
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