javascript - 无法从javascript中的子类访问父类变量
问题描述
我有两个类,一个父类和一个从父类继承的子类。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);
我刚刚意识到在我的实际代码中(这个问题中的代码基于我的实际代码)我在我的子类构造函数中调用了我的子类方法,并且在那个方法中我试图访问我的父类变量。这是其中的一个片段。原来我的问题一直是这个。有人愿意解释为什么会这样吗?
解决方案
如果book_object
是构造函数所需参数的数组,则需要对其进行传播。正确的语法是...variable
,不是${variable}
。
var chapterOne = new Chapter(...book_object)
推荐阅读
- python - 为什么 tf.feature_column.input_layer 以重新排列的顺序返回我的特征值
- apache-spark - 为蒙特卡洛方法尝试 GCP 时出错
- azure - Azure 服务总线中每个实体的最大会话数
- php - 如何在 symfony 中创建一个附加用户的对象
- elasticsearch - Elasticsearch:查询无法返回正确的结果
- angular - 如何在angular4中为每个json数组使用
- microsoft-graph-api - 如何使用 Microsoft graph 获取匿名用户帐户的访问令牌?
- python - 使用 Unix Shell 脚本进行文件解析
- facebook-node-sdk - 广告创意帖子是由处于开发模式的应用创建的。必须在公开场合才能在 Facebook 广告中制作此广告
- r - 将特定列和行求和到 R 中的新矩阵