我正在尝试根据当某个函数触发时更改的其他属性值来更新构造函数的属性。
我已经尝试创建一个函数作为属性,但我仍然会得到相同的结果。
class Rps {
constructor () {
this.userChoice
this.appChoice
this.userPoints = 0
this.pcPoints = 0
this.score = `${this.userPoints} - ${this.pcPoints}`
console.log(score)
this.registeredChoice = []
}
}在我调用一个递增用户和pc积分的函数之后,在我尝试console.log()新对象之后,属性将会更新,但是分数将不会是相同的。分数的值不会改变。
发布于 2019-08-15 02:40:47
getter非常适合这样做:
class Rps {
constructor () {
this.userChoice
this.appChoice
this.userPoints = 0
this.pcPoints = 0
this.registeredChoice = []
}
get score() {
return `${this.userPoints} - ${this.pcPoints}`
}
}或者,不要只更新该函数中对象的属性,还可以调用可以更新score属性的setUser(points)和setPc(points)方法。
https://stackoverflow.com/questions/57500294
复制相似问题