onesiumus
onesiumus

Reputation: 319

Javascript class constructed object is undefined

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

Upvotes: 2

Views: 7841

Answers (2)

jeetaz
jeetaz

Reputation: 731

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();

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

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

Upvotes: 5

Related Questions