1

我有一个对象构造函数,它设置一些属性,然后使用它们连接一个字符串以写入 DOM。我可以看到这在某些情况下有效,但在其他情况下无效。

function Fighter(name, level, attackPts, defencePts, imgSource) {

        // TRUNCATED PROPERTY ASSIGNMENTS AREA:
        this.attackPts = attackPts;
        this.defencePts = defencePts;

        // DOM ELEMENT CONSTRUCTORS:    
        this.img = "style='background: #444 url(" + imgSource + ") no-repeat center'";
        this.char_card_name = "<h3>" + this.name + "</h3>";
        this.char_card_hitdef = "<h4>" + this.attackPts + "/" + this.defencePts + "</h4>";
        this.char_card = "<div class='fighter " +  faction + "' " + "id='" + this.name + "'>" + this.img + this.char_card_name + this.char_card_hitdef + "</div>";

在稍后的游戏功能中,我修改了这个“战斗机”对象的attackdefense点,并且按预期工作,并且我的console.log()测试验证连接的属性也更新。. . . 直到最后的字符串将它们拉在一起并显示:

this.char_card = "<div class='fighter " +  faction + "' " + "id='" + this.name + "'>" + this.img + this.char_card_name + this.char_card_hitdef + "</div>";

当我记录这个属性时,那些攻击和防御数字不会改变,即使它们在之前的属性中成功更新,this.char_card_hitdef

我可以在这里俯瞰什么?我爬遍了整个网络,寻找范围或变量引用问题,但我的日志语句让我回到了这个关键点。

4

1 回答 1

0

因为您仍在构造函数中,所以您需要引用不this. 带参数的变量和 Object 的属性Fighter

所以改变 this.char_card = "<div class='fighter " + faction + "' " + "id='" + this.name + "'>" + this.img + this.char_card_name + this.char_card_hitdef + "</div>";

this.char_card = "<div class='fighter " + faction + "' " + "id='" + name + "'>" + this.img + this.char_card_name + this.char_card_hitdef + "</div>"

以及所有其他引用它们之上的属性的属性。

您可以在此处阅读有关构造函数的更多信息

于 2018-08-29T19:04:15.410 回答