如何创建一个每次使用时都会重新计算的类属性?
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
我希望 test.percent
更改为 100 并适应其他更改。
我可以在不将变量转换为函数的情况下完成此操作吗?
最佳答案
您正在寻找的东西称为getter
。每次访问其属性时都会重新计算 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) //100
关于javascript - JavaScript 中的动态类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58715687/