我在JS中构建保龄球记分卡,我在存储框架内每个单独碗的分数的方式上存在问题。Javascript:在类实例中的对象,从变量中调用值时被重新分配
我这样做是通过将值传递到框架类的实例创建时,并将它们存储在具有firstBowl和secondBowl键的对象中。原因是,我需要从框架外部获取单个碗的价值,以便计算罢工和备用奖金。 (我也尝试使用阵列,并具有相同的问题,详细如下。)
我遇到的问题是,在我的测试中,我创建了一个值为10的firstBowl和0的secondBowl并将其链接到我可以在我的测试中的其他地方调用的变量。但是当我将这次罢工称为罢工时,我发现第一个Bowl和第二个Bowl值已经设置为0,并且总得分仍然是10.如果我在测试中创建了一个新的罢工框架,它的功能与我所期望的一样。
这里是我的框架类的代码:
function Frame(firstBowl, secondBowl = 0){
var bowls = new Object();
bowls.firstBowl = firstBowl;
bowls.secondBowl = secondBowl;
this.score = 0;
this.init = function(){
if (bowls.firstBowl + bowls.secondBowl > 10) {
throw new Error("Illegal Score: Can't be greater than 10")
};
this.score = bowls.firstBowl + bowls.secondBowl
};
this.init();
Frame.prototype.getScore = function(){
return this.score;
};
Frame.prototype.getStatus = function(){
if(bowls.firstBowl === 10) {
return "strike";
}else if(bowls.firstBowl != 10 && this.getScore() === 10) {
return "spare";
}else if(this.getScore() === 0) {
return "gutter";
};
return;
};
Frame.prototype.getBowls = function(){
return bowls;
};
};
,这是有问题的失败的测试:
describe("Frames", function() {
var frame;
var strike;
var spare;
var gutter;
beforeEach(function(){
frame = new Frame(1, 1);
strike = new Frame(10);
spare = new Frame(5,5);
gutter = new Frame(0,0);
});
it("Returns Frame Status as Strike when first bowl is 10", function(){
expect(strike.getStatus()).toEqual("strike")
});
});
,这里是控制台日志框架,当它在它初始化该beforeEach比较功能时,它从测试中调用到:
frameSpec.js:11 --Initialised-
frameSpec.js:12 Frame {score: 10, init: function}
frameSpec.js:13 Object {firstBowl: 10, secondBowl: 0}
frameSpec.js:14 strike
frameSpec.js:15 ------end-------
frameSpec.js:37 ---In Test--
frameSpec.js:38 Frame {score: 10, init: function}
frameSpec.js:39 Object {firstBowl: 0, secondBowl: 0}
frameSpec.js:40 spare
frameSpec.js:41 ------end-------
我已经牛逼对谷歌周围,努力寻找任何东西(我真的发现试图简短地说我的问题简明难度)
任何帮助或见解将不胜感激。我确信我错过了一些非常明显的东西。
比K你乔纳斯真的很清楚,对我很有意义。很明显,我有很多要学习在JS中构造类。再次感谢! –
@si ashbery欢迎;) –