I'm currently trying to write a class that defines a generic getter and setter for all properties of the object. The closest thing I have right now is functions named get and set for the class as a whole which takes a property name and returns it if it exists.
I've tried to use the computed property names option for dynamically defining a getter, but I'm getting errors on either giving the getter arguments, or errors about prop being undefined. Is there any way to define a pair that works for both obj.prop and obj['prop'] that doesn't require writing them for every property in a class?
Current code for reference:
class Holder {
constructor(def="the door"){
this.holds=def
}
// Generic getter for every possible property
get (prop) {
if(prop in this){
return this[prop];
} else {
return `No property found named '${prop}'`;
}
}
// Generic setter, performs magic that sets `changed` as well.
set (prop, value) {
if(prop in this){
this[prop] = value;
this.changed = true;
}
}
}
const hodor = new Holder();
console.log(hodor.holds); // Expected: "the door"
console.log(hodor.derp); // Expected: "No property found named 'derp'"