首页 > 解决方案 > 无法从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);

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

标签: javascript

解决方案


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

var chapterOne = new Chapter(...book_object)

推荐阅读