在JavaScript中通过类使用原型
是否有理由使用原型而不是类?如果我理解正确的话,如果我在构造函数中定义了函数,原型会更有效(但这里不是这样)。这些实现之间唯一不同的是语法吗在JavaScript中通过类使用原型,javascript,Javascript,是否有理由使用原型而不是类?如果我理解正确的话,如果我在构造函数中定义了函数,原型会更有效(但这里不是这样)。这些实现之间唯一不同的是语法吗 class Quiz { constructor(questions) { this.score = 0; this.questionArray = questions; this.questionIndex = 0; } getCurrentQuestionObj() {
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++;
}
}
-
ES6课程只不过是糖。你的两个例子是等价的
关于构造函数中声明的函数,您是对的,这些函数的效率会稍低一些。如果在构造函数中设置“this.foo=function(){}”,则每次使用构造函数实例化时都会创建一个新函数。ES6类只不过是糖。你的两个例子是等价的
关于构造函数中声明的函数,您是对的,这些函数的效率会稍低一些。如果在构造函数中设置“this.foo=function(){}”,则每次使用构造函数实例化时都会创建一个新函数。但是当使用
原型时,可以扩展类定义,而类
符号不太容易扩展。@john_omalley使用类有什么缺点吗?我知道这是ES6附带的最新功能,但我不认为它使用得太频繁。我能想到的唯一缺点是,您需要将它们传输到较旧的浏览器中。re:“类表示法不太容易扩展”。。。不知道你的意思,但它实际上是100%等价的。在Node或Chrome中尝试一下。我知道使用prototype可以扩展第二个实现,但如何扩展类定义?但是当使用prototype
时,可以扩展类定义,虽然class
符号不太容易扩展。@john_omalley使用类有什么缺点吗?我知道这是ES6附带的最新功能,但我不认为它使用得太频繁。我能想到的唯一缺点是,您需要将它们传输到较旧的浏览器中。re:“类表示法不太容易扩展”。。。不知道你的意思,但它实际上是100%等价的。在Node或Chrome中尝试一下。我知道使用prototype可以扩展第二个实现,但如何扩展类定义呢?
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++;
}