0

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++;
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

But when using a prototype you can broader the class definition, while class notation is not so easily expandable.
@john_omalley Is there any downsides of using classes? I know it's a more recent feature that came with ES6, but I don't see it used too often.
The only downside I can think of is that you need to transpile them to work in older browsers.
re: 'class notation is not so easily expandable'... not sure what you mean but it's really 100% equivalent. try it out in Node or Chrome.
I understand using prototype would allow me to expand on the second implementation, but how would I expand on the class definition?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.