首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法从javascript中的子类访问父类变量

无法从javascript中的子类访问父类变量
EN

Stack Overflow用户
提问于 2018-09-27 04:21:09
回答 1查看 2.3K关注 0票数 0

我有两个类,一个父类和一个从父类继承的子类。在初始化子类时,我使用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);

我刚刚意识到,在我的实际代码中(这个问题中的代码是基于我的实际代码),我在子类构造函数中调用了我的子类方法,并且在该方法中,我试图访问我的父类变量。下面是其中的一个片段。原来我的问题一直都是这样的。有人愿意解释一下为什么会发生这种情况吗?

EN

回答 1

Stack Overflow用户

发布于 2018-09-27 04:32:18

如果book_object是构造器所需的参数数组,则需要对其进行扩展。正确的语法是...variable,而不是${variable}

var chapterOne = new Chapter(...book_object)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52525515

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档