Getter对象的任意属性

问题描述 投票:3回答:1

我有一个看起来像这样的课程

export default class {
  constructor () {
    this.store = {}
  }

  setX (x, y) {
    this.store[x] = y
  }
}

当获得未定义的值时,我如何在this.store上定义一个getter来返回0

让我举个例子:

setX('a', 1)将把this.store['a']设置为1

然后this.store['a']会像预期的那样返回1

this.store['b']将返回undefined,但我希望吸气者返回0(并且可能会调用setX('b', 0),还不确定)。

我知道我可以使用Object.defineProperty来定义一个自定义的getter,我无法绕过如何访问store对象的任意的,尚未定义的属性。

这是完全可能还是我必须像这样使用解决方法?

getX (x) {
  return this.store[x] || 0
}

我想避免这种情况,因为this.store[x]似乎更清洁。

javascript oop ecmascript-6 getter
1个回答
3
投票

当获得this.store值时,我如何在0上定义一个getter来返回undefined

除非您能够预测所有可能的属性名称并为其定义getter,否则您需要使用带有Proxyget trap,这是ES2015的新版本(并且不能进行polyfilled)。代理在性能方面很昂贵,只有在你真正需要它们时才使用它们。

例:

class Example {
  constructor () {
    this.store = new Proxy({}, {
      get(target, property) {
        return property in target ? target[property] : 0;
      }
    });
  }

  setX (x, y) {
    this.store[x] = y;
  }
}

const e = new Example();
console.log("Setting a");
e.setX("a", "foo");
console.log("a = " + e.store.a);
console.log("b = " + e.store.b);

当然,如果你将store设为私有,你只能通过对象上的getX方法强制访问,这样可以避免使用代理,代价是在每个实例的基础上定义setXgetX(目前,private data is coming) :

class Example {
  constructor () {
    const store = {};
    this.setX = (x, y) => {
      store[x] = y;
    };
    this.getX = x => {
      return x in store ? store[x] : 0;
    };
  }
}

const e = new Example();
console.log("Setting a");
e.setX("a", "foo");
console.log("a = " + e.getX("a"));
console.log("b = " + e.getX("b"));
© www.soinside.com 2019 - 2024. All rights reserved.