You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS对象中字符串属性引用同对象属性显示undefined问题咨询

问题原因

你遇到的undefined问题有两个核心原因:

  1. 对象初始化时this指向错误:在对象字面量中定义actions字符串时,this并不指向当前正在创建的对象(此时对象还未完成初始化),所以this.attackroll会返回undefined。
  2. 静态字符串无法自动更新:即使后续调用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:08:19