2

New with JavaScript. Can someone help me understand why calling print() returns undefined?

class Quizer {
    constructor(quizObj) {
        this.quiz = quizObj;
    }
    print() {
        console.log(quiz.title);
    }
};
var quizObjects = {
    title: "Quiz1"
};

Constructing:

var quiz = new Quizer(quizObjects);
quiz.print(); //undefined
2
  • where is printAllQuestions()? Commented Apr 12, 2016 at 4:53
  • Ah mistake on my end. I meant print(), not printAllQuestions() Commented Apr 12, 2016 at 5:16

2 Answers 2

5

The problems with your code are,

class Quizer {
    constructor(quizObj) {
      this.quiz = quizObj;
    }
    print() {
      console.log(quiz.title);
      //You are not using the `this` context here to access the quiz
      //you have a variable quiz outside the class declaration that points the instance of this class.
     //That will get hoisted and will be accessed here.

    }
};

var quizObjects = { title: "Quiz1" };
var quiz = new Quizer(quizObjects);
quiz.printAllQuestions(); //undefined
//--------^^^^ printAllQuestions is not a member function of Quizer

Solution:

class Quizer {
    constructor(quizObj) {
      this.quiz = quizObj;
    }
    print() {
      console.log(this.quiz.title);
    }
};

var quizObjects = { title: "Quiz1" };
var quiz = new Quizer(quizObjects);
quiz.print(); //Quiz1
Sign up to request clarification or add additional context in comments.

Comments

1

If you're not much familiar with class syntax yet, the below should work as well.

Quizer = function (quizObj) {
    this.quiz = quizObj;
};
Quizer.prototype = {
    print: function () {
        console.log(this.quiz.title);
    }
}
var quizObjects = { title: "Quiz1" };
var quiz = new Quizer(quizObjects);
quiz.print();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.