Javascript类构造对象未定义

时间:2016-04-12 04:47:27

标签: javascript class

JavaScript的新功能。有人可以帮助我理解为什么调用print()会返回undefined吗?

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

构建

var quiz = new Quizer(quizObjects);
quiz.print(); //undefined

2 个答案:

答案 0 :(得分:5)

您的代码存在问题,

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

解决方案:

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

答案 1 :(得分:1)

如果您还不熟悉类语法,下面的内容也应该有效。

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