对象任意属性的吸气剂

Dec*_*y42 5 javascript oop getter ecmascript-6

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

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

  setX (x, y) {
    this.store[x] = y
  }
}
Run Code Online (Sandbox Code Playgroud)

当获得未定义的值时,我将如何定义一个 getterthis.store来返回0

让我举个例子吧:

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

然后this.store['a']会返回1,正如预期的那样。

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

我知道我可以Object.defineProperty用来定义一个自定义的 getter,我只是无法理解如何访问该store对象的一个任意的、尚未定义的属性。

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

getX (x) {
  return this.store[x] || 0
}
Run Code Online (Sandbox Code Playgroud)

我想避免这种情况,因为this.store[x]看起来更干净。

T.J*_*der 6

在获取值时,我将如何定义一个 getterthis.store来返回?0undefined

除非你可以预测你想要支持的所有可能的属性名称并为它们定义 getter,否则你需要一个带有trapProxy,它是 ES2015 新的(并且不能被填充)。代理在性能方面很昂贵,只有在您真正需要它们时才使用它们。get

例子:

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);
Run Code Online (Sandbox Code Playgroud)

当然,如果您设为store私有,则只能通过getX对象上的方法强制访问,这将避免使用代理,代价是定义setXgetX基于每个实例(目前,私有数据即将到来):

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"));
Run Code Online (Sandbox Code Playgroud)