2017-02-09 78 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类只不过是含糖较多。你的两个例子是相同的。

关于在构造函数中声明的函数 - 你说得对,那些效率会稍差。如果在构造函数中设置'this.foo = function(){}',则每次使用构造函数实例化时都会创建一个新函数。

+0

但是,当使用'prototype'时,你可以扩大类的定义,而'class' notation可以不那么容易扩展。 – MaxZoom

+0

@john_omalley使用类有什么缺点吗?我知道这是ES6附带的更新功能,但我没有看到它经常使用。 –

+0

我能想到的唯一不足就是你需要将它们传输到旧版浏览器中。 –