我是JavaScript的新手,所以我不确定如何问这个问题。我至少有几个文件。
Question.js:
class Questions {
constructor(questions) {
super();
this.questions = questions;
}
startUp() {
console.log(this.questions);
}
}
Answers.js:
class Answers {
constructor() {
super();
this.addQuestions();
}
addQuestions() {
this.question = new Questions();
}
}
我想发生的事情是以某种方式从构造函数继承this.questions并从startUp()在控制台中显示它,但是我总是得到“未定义”。有什么办法吗?
答案 0 :(得分:1)
您的代码中几乎没有错误
super()
中调用class
,这是没有继承的Questions
问题构造函数,因此new Questions()
将返回并以questions:undefined
为对象s
末尾缺少Question
class Questions {
constructor(questions) {
this.questions = questions;
}
startUp() {
console.log(this.questions);
}
}
console.log(new Questions())
class Answers {
constructor() {
this.addQuestions();
}
addQuestions() {
this.questions = new Questions(["Question 1","Question2"]);
}
}
let x = new Answers();
x.addQuestions();
x.questions.startUp();