属性返回原始值而不是通过方法调用更新的值

时间:2013-05-27 02:54:10

标签: javascript

我正在通过EverCraft kata来提高我的Javascript技能并遇到一个小问题,我无法弄清楚如何以我想要的方式开展工作。

我正在使用Jasmine进行测试并进行以下测试:

describe("As an attacker I want to be able to damage my enemies so that they will die and I will live", function () {
    var character = null;

    beforeEach(function () {
        character = new Character();
    });

    it("If attack is successful, other character takes 1 point of damage when hit", function () {

        var beginningHitPoints = character.HitPoints,
            roll = 15;

        character.Attacked(roll);

        expect(character.HitPoints).toBe(beginningHitPoints - 1);
    });
};

此测试失败,因为character.hitPoints为5,但预计它为4。

我的Character对象代码是: (注意:为了简洁起见,我留下了一些与此问题无关的代码)

var Character = function () {
    var hitPoints = 5,
        ...
        attacked = function (roll) {
            var isHit = isAHit(roll);

            if (isAHit) {
                hitPoints = hitPoints - 1;
            }
        }
        ...
    ;

    return {
        ...
        HitPoints: hitPoints,
        Attacked: attacked
        ...
    };
};

我想我明白发生了什么,而不是如何让它按照我的预期运作。我相信当我返回HitPoints: hitPoints时,而不是像我预期的那样返回对var hitPoints = 5的引用,它实际上是返回变量的值。换句话说,该声明相当于HitPoints: 5

我想知道的是,当我致电Attacked时,我是如何让HitPoints返回hitPoints的更新值?

2 个答案:

答案 0 :(得分:0)

您的Character类错误地使用了hitPoints属性,您需要使用getter来获取hitPoints的更新值。

var Character = function(){     var hitPoints = 5,         ...         attacked = function(roll){             var isHit = isAHit(roll);

        if (isAHit) {
            hitPoints = hitPoints - 1;
        }
    }
    ...
;

return {
    ...
    getHitPoints: function(){
        hitPoints;
    },
    Attacked: attacked
    ...
};

};

然后像

一样使用它
var beginningHitPoints = character.getHitPoints(), roll = 15;

答案 1 :(得分:0)

或者,考虑这样的事情,这样你就不必把它变成一个功能:

 var Character = function () {
    return {
       hitPoints: 5,
       attacked: function (roll) {
        this.hitPoints = this.hitPoints - 1;
       }
    };
 };

http://jsfiddle.net/QgVMn/3

在这种情况下,this指的是我们要返回的对象。