将方法的结果保存在 class

Save the result of a method in a class

我想将 属性 的结果保存或存储在 class 中,以便在同一个 class 中的另一个 属性 中使用。我该怎么做?

例如:

class MyClass {

  get randomNumber() {
    let number = Math.floor(Math.random() * 10) + 1
    return number
  }

  get newSum() {
    return this.randomNumber + 1 // I want to use the result from the previous property and add 1 to that
  }

}

```

即时调用randomNumbergetter中的constructor。当您使用 new 关键字创建 MyClass.

的实例时,将调用 contructor

newSum getter 现在 returns 存储的随机数 + 1.

不过,我建议不要对 newSum 属性 使用 getter 模式,因为 getter 不应用于改变值。而是让它成为一个合适的方法。

class MyClass {

  constructor() {
    this.number = this.randomNumber;
  }

  get randomNumber() {
    let number = Math.floor(Math.random() * 10) + 1
    return number
  }

  newSum() {
    return this.number += 1;
  }

}

const instance = new MyClass();
console.log(instance.number); // The random starting number.
console.log(instance.newSum()); // +1
console.log(instance.newSum()); // +1
console.log(instance.newSum()); // +1