我在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歡迎;) –