I would like to overload the "subscription" (python term, let me know if there is a better word in JS world) operation for a specific object in JS.
Just as you can overload the __getitem__ method in python I would like to overload the access to a JS object's properties, for example to throw a custom error if some unset properties are accessed.
Eventually I would like to do the same for affectation to a property.
Is it possible ? If it is, how ?
PS : I found this which is interesting but it would have work only if I knew every properties I could try to get and it is not my case.
What you are asking is metaprogramming. You have to use Javascript Proxy
and Reflect
api.
The proxy api takes a target object and a handler, the methods defined on the handler are called traps, whenever you try to access the key/property of an object the trap gets called first
const target = {
lang: "javascript"
}
const target_t = new Proxy( target, {
get() {// get trap},
set() { // set trap },
construct() { // trap }
...
});
creating an instance of Proxy
does not modify target
,
const target_t = new Proxy( target, {
get(target,key,value) {
if ( key in target )
return Reflect.get(target,key);
throw new Error(`${key} does not exists in target`);
}
});
console.log(targe_t.lang); // javascript
console.log(target_t.lnag); // throws error