JS对象中字符串属性引用同对象属性显示undefined问题咨询
问题原因
你遇到的undefined问题有两个核心原因:
- 对象初始化时
this指向错误:在对象字面量中定义actions字符串时,this并不指向当前正在创建的对象(此时对象还未完成初始化),所以this.attackroll会返回undefined。 - 静态字符串无法自动更新:即使后续调用
Attack()方法赋值了attackroll,actions作为静态字符串,不会自动同步最新的attackroll值。
解决方案
下面提供两种实用的解决思路:
方案1:使用getter动态生成actions
将actions改为getter方法,这样每次访问actions时都会自动拼接最新的attackroll值:
const creature = { str: 18, proficiency: 2, attackroll: "", Attack: function() { this.attackroll = (this.proficiency + Math.floor((this.str - 10)/2)).toString(); console.log(this.attackroll); }, // 用getter动态生成actions内容 get actions() { return `Bite. +${this.attackroll} to hit, reach 5ft, one target. Hit: 16 (3d8 + 4 piercing damage).`; } }; // 使用步骤 creature.Attack(); // 先计算attackroll console.log(creature.actions); // 此时会输出带正确数值的actions内容
优势:无需手动维护actions的更新,每次访问都会自动使用最新的attackroll值,适合attackroll可能多次变化的场景。
方案2:在Attack方法中同步更新actions
如果attackroll只需要计算一次,可以在Attack()方法中直接更新actions字符串:
const creature = { str: 18, proficiency: 2, attackroll: "", actions: "", Attack: function() { this.attackroll = (this.proficiency + Math.floor((this.str - 10)/2)).toString(); // 同步更新actions this.actions = `Bite. +${this.attackroll} to hit, reach 5ft, one target. Hit: 16 (3d8 + 4 piercing damage).`; console.log(this.attackroll); } }; // 使用步骤 creature.Attack(); // 计算attackroll并同步更新actions console.log(creature.actions); // 输出正确内容
优势:逻辑更直接,适合不需要动态更新actions的场景,性能略优(不会每次访问都重新拼接字符串)。
内容的提问来源于stack exchange,提问作者Justin Logue
相关产品推荐
相关产品推荐

