Let's say we have an Object:
const obj = {
foo: bar,
boop: "beep",
}
Now I would like to add some functionality that occurs any time a property is set (also get for this matter actually) in this object. Let's just keep it simple and say the added functionality is just a console.log("a set/get action was just triggered on obj!")
.
How can I achieve this?
Advanced extension:
Naming the the property that was set and the value it was set with.
some sample behavior for clarity:
// simple:
obj.foo = "not bar anymore!";
// console output: a set/get action was just triggered on obj!
obj.rand = "a randomly added prop here";
// console output: a set/get action was just triggered on obj!
// advanced:
obj.boop = "burp";
// console output: a set/get action was just trigged on obj with prop: "boop", value: "burp".
obj.newRand = "a new randomly added prop here";
// console output: a set/get action was just trigged on obj with prop: "newRand", value: "a new randomly added prop here";
Bonus:
Any other ways to solve this issue are welcome.
JavaScript Accessors (Getters and Setters)ECMAScript 5 (ES5 2009) introduced Getter and Setters. Getters and setters allow you to define Object Accessors (Computed Properties).
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
In JavaScript, accessor properties are methods that get or set the value of an object. For that, we use these two keywords: get - to define a getter method to get the property value. set - to define a setter method to set the property value.
Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed.
Use a Proxy object with getter/setter traps instead.
The traps in the Proxy object allow you to interject the object methods with your custom functionality while returning the actual object data in the end of the process.
Code example:
const obj = {
foo: 'bar',
boop: "beep",
};
const objProx = new Proxy(obj, {
get(obj, prop) {
console.log('On obj', obj, 'getting', prop);
return obj[prop];
},
set(obj, prop, newVal) {
console.log('On obj', obj, 'setting', prop, 'to', newVal);
return obj[prop] = newVal;
},
});
objProx.boop = "burp";
objProx.newRand = "a new randomly added prop here";
// invokes getter:
objProx.foo;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With