Last active
December 22, 2016 16:09
-
-
Save maurobringolf/e329a5e7bc98cf4e559b1e5eacc83b9d 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 restricted access property o.x using getters and setters | |
var o = { | |
c: 0, | |
get x() { return this.c; }, | |
set x(y) { this.c = Math.max(y,0); } | |
} | |
o.x = 3; | |
o.x; //3 | |
o.x = -4; | |
o.x; //0 | |
//can be broken | |
o.c = -4; | |
o.x; //-4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment