Javascript class constructed object is undefined - Stack Overflow

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

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

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
Share Improve this question edited Apr 12, 2016 at 5:15 onesiumus asked Apr 12, 2016 at 4:47 onesiumusonesiumus 3318 silver badges28 bronze badges 2
  • where is printAllQuestions()? – Satej S Commented Apr 12, 2016 at 4:53
  • Ah mistake on my end. I meant print(), not printAllQuestions() – onesiumus Commented Apr 12, 2016 at 5:16
Add a ment  | 

2 Answers 2

Reset to default 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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744229365a4564168.html

相关推荐

  • Javascript class constructed object is undefined - Stack Overflow

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

    8天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信