Javascript类构造的对象未定义

Javascript class constructed object is undefined

本文关键字:对象 未定义 Javascript      更新时间:2024-04-29

新增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

代码的问题是,

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

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

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