【问题标题】:How do I get the computed getter name in Javascript?如何在 Javascript 中获取计算的 getter 名称?
【发布时间】:2020-07-13 01:34:24
【问题描述】:

我有类似这样的代码:

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

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

以上代码无效,因为val不存在。

我想从getter 中获取computed getter 名称并添加到变量val,这样我就知道正在访问什么属性。

我怎样才能做到这一点?

【问题讨论】:

  • 您可能正在寻找代理 - 否则您无法在对象中拥有“包罗万象”的 getter。
  • 为什么还要在这里使用计算属性名称?很明显,你的 getter 应该有名称a,所以写get a() { return this._a; }。请发布您的实际代码并告诉我们更多关于您的实际问题。
  • 请注意,“计算”并不意味着“动态”。它所做的只是在创建属性时从表达式计算属性的名称 - 当声明 class 时,一次。

标签: javascript function class getter computed-properties


【解决方案1】:

欢迎使用 Stack Overflow!

您正在寻找的是代理。这些代理不能由普通类扩展,但您可以确保您的类将自己实例化为代理。像这样

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);

【讨论】:

    【解决方案2】:

    你不能使用普通的类语法和 getter/setter 来做到这一点。问题是你只能定义 concrete getter。

    为了定义一个拦截所有调用的getter,你需要使用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);

    如果您想“隐藏”某些字段,例如以下划线开头的任何内容,您可以执行以下操作:

    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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-18
      • 1970-01-01
      • 2010-12-18
      • 2022-10-17
      • 2011-04-02
      • 2018-03-21
      相关资源
      最近更新 更多