Reputation: 519
Is there a reason to use prototypes over classes? If I understand correctly, prototypes would be more efficient if I had defined functions in the constructor (but that is not the case here). Is the only thing different between these implementations syntax?
class Quiz {
constructor(questions) {
this.score = 0;
this.questionArray = questions;
this.questionIndex = 0;
}
getCurrentQuestionObj() {
return this.questionArray[this.questionIndex];
}
isGameOver() {
return this.questionArray.length === this.questionIndex;
}
guess(answer) {
if(this.getCurrentQuestionObj().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
}
-
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getCurrentQuestionObj = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.isGameOver = function() {
return this.questions.length === this.questionIndex;
}
Quiz.prototype.guess = function(answer) {
if(this.getCurrentQuestionObj().correctAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Upvotes: 0
Views: 36
Reputation: 1398
ES6 classes are nothing more than sugar. Your two examples are equivalent.
Regarding functions declared in the constructor - you're right that those would be slightly less efficient. If you set 'this.foo = function() {}' in the constructor a new function is created every time you instantiate using the constructor.
Upvotes: 2