2017-02-09 6 views
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++; 
} 

答えて

2

ES6のクラスは、砂糖以外の何物でもありません。あなたの2つの例は同等です。

コンストラクタで宣言されている関数については、それらはやや効率が悪いでしょう。 'this.foo = function(){}'をコンストラクタに設定すると、コンストラクタを使用してインスタンス化するたびに新しい関数が作成されます。

+0

しかし、 'prototype'を使うと、クラス定義を広げることができますが、' class'表記はあまり簡単に拡張できません。 – MaxZoom

+0

@john_omalleyクラスを使用する際の弱点はありますか?私はそれがES6に付属するより最近の機能だと知っていますが、あまり頻繁に使用されているとは思いません。 –

+0

私が考えることができる唯一の欠点は、古いブラウザで動作させるためにそれらを切り抜く必要があることです。 –

関連する問題