Reputation: 227
How do you make a class property that recalculates each time you use it?
class myClass {
constructor(x, y) {
this.x = x
this.y = y
this.percent = x/y * 100
}
}
var test = new myClass(5, 10)
test.percent
//50
test.x = 10
test.percent
//still 50
I want test.percent
to change 100 and adapt to other changes.
Can I do this without turning the variable into a function?
Upvotes: 0
Views: 77
Reputation: 8650
You can use an accessor ( getter
) to alter the data each time you are accessing it.
In your case, you can replace the percent property by a getter.
class myClass {
constructor(x, y) {
this.x = x
this.y = y
}
get percent() {
return this.x / this.y * 100;
}
}
var test = new myClass(5, 10)
console.log(test.percent);
//50
test.x = 10
console.log(test.percent);
//now 100
I have also edited your code to use this
to access x
and y
Upvotes: 1
Reputation: 33870
What you are looking for is called a getter
. A getter is recomputed everytime its property is accessed:
class myClass {
constructor(x, y) {
this.x = x
this.y = y
}
get percent(){
return this.x / this.y * 100
}
}
var test = new myClass(5, 10)
console.log(test.percent) //50
test.x = 10
console.log(test.percent) //100
Upvotes: 4
Reputation: 37755
There are two ways you can do this
this.percent
as a functionclass myClass {
constructor(x, y) {
this.x = x;
this.y = y
this.percent = function() {
return this.x / this.y * 100
}
}
}
var test = new myClass(5, 10)
console.log(test.percent())
test.x = 10
console.log(test.percent())
getter
class myClass {
constructor(x, y) {
this.x = x;
this.y = y;
}
get percent() {
return this.x / this.y * 100
}
}
var test = new myClass(5, 10)
console.log(test.percent)
test.x = 10
console.log(test.percent)
Upvotes: 1