How do I get the computed getter name in Javascript?

Viewed 742

I have this code similar to this:

class A {                                                            
    constructor() {
        this._a = 1;
    }

    get [val]() {
        if (val == 'a') {
             return this._a;
        }
    }
}

The above code is not valid, because val doesn't exist.

I want to get the computed getter name from within the getter and add to a variable val, so that I would know what property is being accessed.

How can I achieve this?

2 Answers

welcome to Stack Overflow!

What you are looking for is a Proxy. These Proxies cannot be extended by normal classes, but you can ensure that your class instantiates itself as a Proxy instead. Like this

class A {
    constructor() {
        this._a = 1;
        return new Proxy(this, {
            get: (object, key, proxy) => {
                if (key == 'a') {
                   return object._a;
                }
            }
        });
    }
}
let someInstance = new A();
console.log(someInstance.a);

You cannot do that using the normal class syntax and getters/setters. The problem is that you can only define concrete getters.

In order to define a getter that intercepts all calls you need to use a Proxy

class A {
  constructor() {
    this._a = 1;
  }
}

const handler = {
  get: function(obj, prop) {
    if (prop == 'a') {
      return obj._a;
    }
    
    return `getting "${prop}" instead of "a"`;
  }
};


const instance = new A();
const p = new Proxy(instance, handler);

console.log(p.a);
console.log(p.b);
console.log(p._a);

If you want to "hide" certain fields, like anything that starts with an underscore, you can do something like:

class A {
  constructor() {
    this._a = 1;
    this._b = 2;
    this._c = 3;
  }
}

const handler = {
  get: function(obj, prop) {
    const secretProp = `_${prop}`;
    //check if a property that starts with underscore is in the source object
    if (secretProp in obj) {
      return obj[secretProp];
    }
    
    return `getting "${prop}" is not allowed`;
  }
};


const instance = new A();
const p = new Proxy(instance, handler);

console.log(p.a);
console.log(p.b);
console.log(p.c);

console.log(p._a);
console.log(p._b);
console.log(p._c);

console.log(p.foo);

Related