【发布时间】:2018-09-26 20:21:08
【问题描述】:
我有两个类,一个父类和一个从父类继承的子类。初始化子类时,我使用 super() 关键字调用父类的构造函数。然后我尝试在子方法中访问父类变量。但是,当我尝试这样做时,我收到此错误:Cannot read property 'undefined'。为什么变量未定义?构造函数没有像我预期的那样工作吗?
class Book {
constructor(title, author, chapters) {
this.title = title; //string
this.author = author; //string
this.chapters = chapters; //array of strings
}
getTitle() {
return this.title;
}
getAuthor() {
return this.author;
}
}
class Chapter extends Book {
constructor(title, author, chapters, numberPages, subject, time, chapterIndex) {
super(title, author, chapters);
this.numberPages = numberPages;
this.subject = subject;
this.time = time;
this.chapterIndex = chapterIndex;
}
getChapterText() {
return this.chapters[this.chapterIndex];
}
}
var chapterOne = new Chapter("title", "author", ["lorem ipsum...", "lorem ipsum...", "lorem ipsum..."], 42, "about lorem ipsum", "3:01", 0); //book_object is an array of everything the chapter constructor needs
console.log(chapterOne.getChapterText());
我也尝试过使用super.chapters 来访问父类变量,但我得到了这个错误:unexpected keyword super。
更新
也许使用${book_object} 让我的问题太混乱了。这个 javascript 作为 JSP(java 服务器页面)运行。因此,它在提供服务之前被编译。我更新了我的问题以减少混淆。
更新 2
class Book {
constructor(title, author, chapters) {
this.title = title; //string
this.author = author; //string
this.chapters = chapters; //array of strings
}
getTitle() {
return this.title;
}
getAuthor() {
return this.author;
}
}
class Chapter extends Book {
constructor(title, author, chapters, numberPages, subject, time, chapterIndex) {
super(title, author, chapters);
this.numberPages = numberPages;
this.subject = subject;
this.time = time;
this.currentChapter = this.getChapterText(); //I forgot to include this line in my original question.
this.chapterIndex = chapterIndex;
}
getChapterText() {
return this.chapters[this.chapterIndex];
}
}
var chapterOne = new Chapter("title", "author", ["lorem ipsum...", "lorem ipsum...", "lorem ipsum..."], 42, "about lorem ipsum", "3:01", 0); //book_object is an array of everything the chapter constructor needs
console.log(chapterOne.currentChapter);
我刚刚意识到在我的实际代码中(这个问题中的代码基于我的实际代码)我在我的子类构造函数中调用我的子类方法,并且在该方法中我试图访问我的父类变量.这是其中的一个sn-p。原来我的问题一直是这个。有人愿意解释为什么会这样吗?
【问题讨论】:
-
为什么
Chapter是Book的子类?一本书可以包含多个章节,因此一章不是一本书。 -
当您调用
new Chapter()时,您没有提供chapters参数,因此它是未定义的。所以this.chapters = chapters将其设置为undefined。该问题与访问父属性无关。 -
按照您的设置方式,一章也是一本书,只是一种特殊的书。此处没有可访问的父级。
-
@Barmar 抱歉,但事实并非如此。语义无关紧要,如果您考虑由书组成的书,那么一章肯定也是一本书。
-
什么是
${book_object}?这不是变量的有效语法。它看起来像模板文字中使用的语法。
标签: javascript