[英]Increasing,decreasing and total JavaScript
I have a beginner predeterminate exercise in React js, but I don´t know how to do it without a "state" when I try set the counter.我在 React js 中有一个初学者预先确定的练习,但是当我尝试设置计数器时,我不知道如何在没有“状态”的情况下做到这一点。
Can anyone help me?谁能帮我?
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());
My exercise have to show the following:我的练习必须显示以下内容:
In vanilla JS you don't have any states built-in.在 vanilla JS 中,您没有内置任何状态。 You just change the value of a property.
您只需更改属性的值。
With the ++
and --
operators you can add or subtract with a value of 1. So in the increaseOne
and decreaseOne
methods change the value of the this.counter
property.使用
++
和--
运算符,您可以添加或减去值 1。因此在increaseOne
和this.counter
decreaseOne
的值。
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);
For the getValue()
method you can also use a getter method, which acts like a property but actually returns the result of a function.对于
getValue()
方法,您还可以使用getter方法,它的作用类似于属性,但实际上返回 function 的结果。 But this is just a suggestion and should make little difference.但这只是一个建议,应该没什么区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.