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' notation可以不那么容易扩展。 – MaxZoom
@john_omalley使用类有什么缺点吗?我知道这是ES6附带的更新功能,但我没有看到它经常使用。 –
我能想到的唯一不足就是你需要将它们传输到旧版浏览器中。 –