Created
February 19, 2017 15:25
-
-
Save simonlc/886e078b672f0d991e24136e76c922fd to your computer and use it in GitHub Desktop.
private fields using closuers
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
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