I want to save or store the outcome of a property in a class to use in another property in the same class. How do I do that?
for example:
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
}
}
```
Instantly call the randomNumber
getter in the constructor
. The contructor
is called when you use the new
keyword to create an instance of MyClass
.
The newSum
getter now returns the stored random number + 1
.
Though, I would recommend not using the getter pattern for the newSum
property as a getter should not be used to mutate values. Instead make it a proper method.
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments