增加,减少和增加JavaScript

时间:2020-05-18 14:20:18

标签: javascript class constructor properties

我在React js中有一个初学者的预定练习,但是当我尝试设置计数器时,我不知道如何在没有“状态”的情况下进行操作。

有人可以帮助我吗?

class Counter {
  constructor() {
    //initialization of the counter variable
    this.counter = 0;
  }
  increaseOne() {
    //increase the value in one
  }
  decreaseOne() {
    //decrease the value in one
  }
  getValue() {
    //return the value
  }
}

let myNewCounter = new Counter();
myNewCounter.increaseOne();
console.log(myNewCounter.getValue());
myNewCounter.increaseOne();
myNewCounter.increaseOne();
console.log(myNewCounter.getValue());
myNewCounter.decreaseOne();
myNewCounter.decreaseOne();
console.log(myNewCounter.getValue());

我的锻炼必须显示以下内容:

enter image description here

1 个答案:

答案 0 :(得分:1)

在普通JS中,您没有内置任何状态。您只需更改属性的值即可。

使用++--运算符,您可以添加或减去1。因此,在increaseOnedecreaseOne方法中,更改{{ 1}}属性。

this.counter

对于class Counter { constructor() { this.counter = 0; } increaseOne() { this.counter++; } decreaseOne() { this.counter--; } get value() { return this.counter; } } let myNewCounter = new Counter(); myNewCounter.increaseOne(); console.log(myNewCounter.value); myNewCounter.increaseOne(); myNewCounter.increaseOne(); console.log(myNewCounter.value); myNewCounter.decreaseOne(); myNewCounter.decreaseOne(); console.log(myNewCounter.value);方法,您还可以使用 getter 方法,该方法的作用类似于属性,但实际上返回函数的结果。但这只是一个建议,应该没有什么区别。

相关问题