In this tutorial, we are going to see how to get the different values of object properties on each access in JavaScript.
JavaScript objects are very flexible and make it easier to work with language but there often complex to completely understand especially if you are just getting started.
I recently encountered a problem where I had to get the incremented value of the object property every time it was accessed.
let obj = { i: 0 }; console.log(obj.i); // 1 console.log(obj.i); // 2 console.log(obj.i); // 3
I thought of solving this by creating a constructor using getter and setter, but the problem was object was already provided and we could just modify it.
The one solution that came to my mind was using Proxy, it is a powerful concept but not often used during development.
Proxy allows us to extend the existing object and return a proxy object with the getter and setters in which we can achieve the modification of property values.
obj = new Proxy(obj, { get: (target, property) => { if(property === 'i'){ target[property] = target[property] + 1; return target[property]; } } });
This will increment the value of the property i
every time it is accessed.
console.log(obj.i); // 1 console.log(obj.i); // 2 console.log(obj.i); // 3