2

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.

WIP
  • 348
  • 2
  • 11
  • 3
    For some objects, yes; look at [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). If by “affectation” you mean assignment, then yes, the `set` trap does that. – Sebastian Simon Mar 26 '18 at 19:00

2 Answers2

1

You can do a tremendous amount with proxies, but if you just want to control access of a property you can use simple getters/setters. For example:

let obj = {
    _prop: "Some value",
    get prop() {
        console.log("accessing prop")
        return this._prop
    },
    set prop(value){
        console.log("setting prop")
        this._prop = value
    }
}

console.log("value is: ", obj.prop)
obj.prop = "new value"
console.log("new value is: ", obj.prop)
Mark
  • 90,562
  • 7
  • 108
  • 148
1

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
0.sh
  • 2,659
  • 16
  • 37