Search code examples
javascriptgetter-setteres6-classes6-proxy

How to make a getter proxy for all instances of a class in javascript?


Proxies can be used to define 'general getters' for objects. For example

var obj = {'a':3, 'b':4 };
var proxy = new Proxy( obj, {
    get: function(obj, prop){return obj[prop]+10} 
} );
proxy.a //13

I have a vector class that extends Array:

class vec extends Array{
   constructor(...a){
      super(...a)    
   }
   get x(){
      return this[0];
   }
   /* some more functions */
}

and I want the index to wrap around like in python. For example if v is a vector I want v[-1] to return the last element of v. To do this I would need to wrap a proxy around each vector instance (I think) so I could clamp the index. But I don't know how to make a proxy for all instances I only know how it works for a single object. So how would you do this?


Solution

  • You could create your class so that it returns a instance of a proxy, and on that proxy you create a get method where you add your custom logic.

    class Vec extends Array {
      constructor(...a) {
        super(...a)
    
        return new Proxy(this, {
          get: function(target, prop, receiver) {
            const n = +prop;
    
            if (!isNaN(n) && n < 0) {
              return [...target].slice(n)
            }
    
            return Reflect.get(...arguments);
          }
        })
      }
    
      get x() {
        return this[0];
      }
    }
    
    const v = new Vec(1, 2, 3);
    console.log(v[-1])
    console.log(v[-2])
    console.log(v.x)