gpt4 book ai didi

Javascript类构造的对象未定义

转载 作者:行者123 更新时间:2023-11-29 16:07:54 24 4
gpt4 key购买 nike

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

关于Javascript类构造的对象未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36563816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com