我正在通过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
的更新值?
答案 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;
}
};
};
在这种情况下,this
指的是我们要返回的对象。