Skip to content

Instantly share code, notes, and snippets.

@simonlc
Created February 19, 2017 15:25
Show Gist options
  • Save simonlc/886e078b672f0d991e24136e76c922fd to your computer and use it in GitHub Desktop.
Save simonlc/886e078b672f0d991e24136e76c922fd to your computer and use it in GitHub Desktop.
private fields using closuers
function Registry(defaultValue){
const defaultValue = defaultValue;
const values = Object.create(null);
// These functions will always have access to the above variables. Javascript creates
// a closure when functions are created, so the outer scope is available to it.
// These first two functions are public
this.register = function(name, value){
values[name] = value;
};
this.getValue = function(name){
let value;
if (Object.prototype.hasOwnProperty.call(values, name)){
value = values[name];
} else {
value = defaultValue;
}
return value;
};
function privateMethod() {
// can't be called from outside this constructor (gets hoisted to the top so we can define it here)
}
}
Register.prototype.publicPrototypeMethod() {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment