您如何制作一个每次使用都会重新计算的类属性?
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并适应其他更改。
我可以不将变量变成函数吗?
答案 0 :(得分:4)
您要寻找的被称为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
答案 1 :(得分:1)
有两种方法可以做到这一点
this.percent
作为函数
class 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)
答案 2 :(得分:1)
您可以在每次访问数据时使用访问器(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
我还编辑了您的代码,以使用this
访问x
和y