0
プロトタイプをクラスに使用する理由はありますか?私が正しく理解していれば、コンストラクタで関数を定義していればプロトタイプがより効率的になります(ただし、ここではそうではありません)。これらの実装構文の間で唯一の違いはありますか?プロトタイプをJavaScriptで使用する
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++;
}
しかし、 'prototype'を使うと、クラス定義を広げることができますが、' class'表記はあまり簡単に拡張できません。 – MaxZoom
@john_omalleyクラスを使用する際の弱点はありますか?私はそれがES6に付属するより最近の機能だと知っていますが、あまり頻繁に使用されているとは思いません。 –
私が考えることができる唯一の欠点は、古いブラウザで動作させるためにそれらを切り抜く必要があることです。 –