Last active
December 22, 2016 16:09
-
-
Save maurobringolf/a0a2914639a4a901238b5e4f6084a70f to your computer and use it in GitHub Desktop.
Getter and Setter methods for object properties in JavaScript: https://medium.com/@maurobringolf/javascript-data-encapsulation-and-property-getter-and-setter-methods-a59cbddf2ef4#.qimkogc2u
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
//defining a pseudo-private property o.x using getters and setters | |
var o = { | |
__c: 1, | |
get x() { return this.__c; }, | |
set x(y) { this.__c = y; } | |
} | |
//Make the property o.__c non-enumerable | |
Object.defineProperty(o, '__c', { enumerable: false }); | |
//Object.keys and for...in loop skip x.c now | |
Object.keys(o); //["x"] | |
//The property can still be accessed using its name | |
o.__c = 2; | |
o.__c; //2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment