首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以使用实例的属性来更新其他属性?

问是否可以使用实例的属性来更新其他属性?
EN

Stack Overflow用户
提问于 2019-08-15 02:37:24
回答 1查看 23关注 0票数 0

我正在尝试根据当某个函数触发时更改的其他属性值来更新构造函数的属性。

我已经尝试创建一个函数作为属性,但我仍然会得到相同的结果。

代码语言:javascript
复制
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()新对象之后,属性将会更新,但是分数将不会是相同的。分数的值不会改变。

EN

回答 1

Stack Overflow用户

发布于 2019-08-15 02:40:47

getter非常适合这样做:

代码语言:javascript
复制
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)方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57500294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档