Auto Getter/Setters
by Scott Kaye
JavaScript
"use strict";
function Shoes() {
this._color = null;
this._style = null;
};
Object.keys(new Shoes()).forEach(field => {
let name = field.slice(1); // Remove underscore
// Option 1
// Dynamically create chainable getter/setter functions for each private field
// cool_shoes.color("red") sets _color to "red"
// cool_shoes.color() returns "red"
Shoes.prototype[name] = function(val) {
if (val) {
this[field] = val;
return this;
}
return this[field];
};
// Option 2
// Dynamically create syntactic getters and setters
// cool_shoes.style = "Some style" sets _style to "Some style" (not a new .style field!)
// cool_shoes.style returns "Some style"
/*Object.defineProperty(Shoes.prototype, name, {
get: function() {
return this[field];
},
set: function(val) {
this[field] = val;
}
});*/
});
let cool_shoes = new Shoes().color("glitter").style("platform");
// With option 2:
// cool_shoes.style = "some other style";
console.clear();
console.log("final object:", cool_shoes)
console.log("color():", cool_shoes.color())
console.log("style():", cool_shoes.style());