【问题标题】:How does this object auto increment? [closed]这个对象如何自动递增? [关闭]
【发布时间】:2019-03-05 12:01:35
【问题描述】:

我知道它为什么起作用,但它是如何起作用的,我不太确定。我假设它与 this.count = this.count + 1 等于 ++ 有关,但为什么它不只是增加 1 而不是增加 5?

class Multiplier {
  constructor() {
    this.count = 1
  }
  increment() {
    this.count = this.count + 1;
  }
  apply(x) {
    return this.count * x;
  }
}

let multiplier = new Multiplier();
console.log(multiplier.apply(5)); //multiplier.apply(5) = 5
multiplier.increment(); //miltiplier.increment(++) = 10
multiplier.increment(); //multiplier.increment(++) = 15
console.log(multiplier.apply(5)); // 15*

【问题讨论】:

  • 它确实增加了 1,而不是 5。
  • 在您的情况下,执行两个multiplier.increment() 使this.count 等于3。然后,3 * 5 = 15
  • 这很有意义!感觉很傻。。

标签: javascript object constructor


【解决方案1】:
apply(x) {
    return this.count * x;
}

这不会改变您的 count 值。它只是返回一个值,它是count 和 5 的乘积。

你可以考虑改写如下:

apply(x) {
    this.count = this.count * x;
    return this.count;
}

【讨论】:

    【解决方案2】:

    使用正确的应用方法:

    apply(x) {
        return this.count *= x;
    }
    

    【讨论】:

      【解决方案3】:

      它的工作原理如下:

      let multiplier = new Multiplier();
      console.log(multiplier.apply(5)); //multiplier.apply(5) = 5
      multiplier.increment(); // this.count = 1 + 1 =2;
      multiplier.increment(); // this.count = 2 + 1 =3
      console.log(multiplier.apply(5)); // 3 * 5 =15
      

      改正

       return this.count *= x;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-11
        • 1970-01-01
        • 2012-02-08
        • 1970-01-01
        • 1970-01-01
        • 2015-01-14
        • 2015-01-21
        • 2016-03-07
        相关资源
        最近更新 更多