Reputation: 93
I am currently trying to translate some ruby code into Javascript.
This is what I have written:
class Bowling {
constructor (){
this.frame = 1;
this.score = 0;
this.is_spare = false;
this.is_strike = false;
this.is_double = false;
}
game(ball_1, ball_2){
if(this.is_double == true){
var frame_score = ball_1 + (ball_1 + ball_2) * 2;
}
else if(this.is_strike == true){
if(ball_1 == 10)
this.is_double = true;
frame_score = (ball_1 + ball_2) * 2;
}
else if(this.is_spare == true){
frame_score = ball_1 * 2 + ball_2;
}
else{
frame_score = ball_1 + ball_2;
}
if(ball_1 == 10){
this.is_strike = true;
this.is_spare = false;
}
else if(ball_1 + ball_2 == 10){
this.is_spare = true;
this.is_double = false;
this.is_strike = false;
}
else{
this.is_spare = false;
this.is_strike = false;
this.is_double = false;
}
this.score = this.score + frame_score;
}
}
When I call game(1,2) on a new bowling object the result is not 3, but undefined and I can't see why.
Upvotes: 0
Views: 41
Reputation: 2834
This is happening because you have to return this.score
. If you don't, the method doesn't know what to return, and like a lot of other programming languages returns undefined
or a similar value.
class Bowling {
constructor() {
this.frame = 1;
this.score = 0;
this.is_spare = false;
this.is_strike = false;
this.is_double = false;
}
game(ball_1, ball_2) {
if (this.is_double == true) {
var frame_score = ball_1 + (ball_1 + ball_2) * 2;
} else if (this.is_strike == true) {
if (ball_1 == 10)
this.is_double = true;
frame_score = (ball_1 + ball_2) * 2;
} else if (this.is_spare == true) {
frame_score = ball_1 * 2 + ball_2;
} else {
frame_score = ball_1 + ball_2;
}
if (ball_1 == 10) {
this.is_strike = true;
this.is_spare = false;
} else if (ball_1 + ball_2 == 10) {
this.is_spare = true;
this.is_double = false;
this.is_strike = false;
} else {
this.is_spare = false;
this.is_strike = false;
this.is_double = false;
}
this.score = this.score + frame_score;
return this.score
}
}
var x = new Bowling()
console.log(x.game(1, 2))
MDN states that:
To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is undefined.
Upvotes: 1