0

So I get SyntaxError: Unexpected token { on line "Question.prototype.displayQuestion() { ". But code looks fine. Anyone know what is going on?

function Question(question, answers, correct){
    this.question = question;
    this.answers = answers;
    this.correct = correct;
}

Question.prototype.displayQuestion(){
    console.log(this.question);

    for(var i=0; i<this.answers.length; i++){
        console.log(i + " : " + this.answers[i]);
    } 
} 
Aleksandar
  • 51
  • 7
  • 1
    No, the code doesn't look fine. Prototype properties must be created by assignment, there is no "method" syntax. – Bergi Jan 26 '19 at 19:02

1 Answers1

2

You need to assign a function to the prototype.

Question.prototype.displayQuestion = function() {
    // ...
};

function Question(question, answers, correct) {
    this.question = question;
    this.answers = answers;
    this.correct = correct;
}

Question.prototype.displayQuestion = function() {
    console.log(this.question);
    for (var i = 0; i < this.answers.length; i++) {
        console.log(i + " : " + this.answers[i]);
    }
}

var question = new Question(['q1', 'q2', 'q3'], ['a', 'b', 'c'], []);

question.displayQuestion();
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392