JavaScript调用对象方法修改property属性值不生效该如何解决?
问题原因
你代码中hoursTrained方法里的两行逻辑仅执行了算术计算,没有将计算结果赋值回对象属性:
this.energy - hours只是计算了energy减去训练时长的结果,没有把这个结果重新赋值给this.energythis.experience + hours同理,仅计算了相加的结果,没有覆盖原来的experience属性值
所以对象的属性自始至终都没有被修改,运行测试代码时自然看到输出数值没有变化。
修复方案
把算术运算替换为复合赋值运算符即可,或者写完整的赋值语句,两种写法效果完全一致:
修复后的完整代码:
let athlete = { energy:100, experience: 10, hoursTrained: function(hours) { // 复合赋值运算符写法,简洁直观 this.energy -= hours this.experience += hours // 也可以写完整赋值语句: // this.energy = this.energy - hours // this.experience = this.experience + hours } }
修复后运行你的测试代码,输出结果会符合预期:
Before of to start the training
Energy of the athlete: 100
Experience of the athlete: 10
Athlete after of the training
Energy of the athlete 95
Experience of the athlete 15
内容的提问来源于stack exchange,提问作者Jose Erasmo Hernandez Yate
相关产品推荐
相关产品推荐

