“无法访问未初始化的变量。”在类构造函数中

时间:2019-10-24 10:45:11

标签: javascript ecmascript-6 es6-class

我的Javascript代码中有两个非常简单的类:

class Renderable{
    toHTML(){
        return '';
    }
}


class Intro extends Renderable{
    constructor(title, pretitle, backgroundImage){
        debugger;
        this.title = title;
        this.pretitle = pretitle;
        this.backgroundImage = backgroundImage;
    }
    [...]
}

这样的代码按顺序排列,因此不会出现任何吊装问题。但是,当我加载网页时,出现以下错误:

ReferenceError: Cannot access uninitialized variable.在构造函数中的this.title = title;行。当我打开调试器时,发现this确实是undefined。我在做什么错了?

2 个答案:

答案 0 :(得分:2)

您需要在子类中调用super(),就像MDN explains:“在构造函数中使用时,super关键字会单独出现,并且必须在使用之前使用 < / strong>。”

class Renderable{
    toHTML(){
        return '';
    }
}


class Intro extends Renderable{
    constructor(title, pretitle, backgroundImage){
        super()
        this.title = title;
        this.pretitle = pretitle;
        this.backgroundImage = backgroundImage;
    }
}
const intro = new Intro('title', 'pretitle', 'bg.jpg')
alert(intro.title)

答案 1 :(得分:1)

只需添加此行

class Intro extends Renderable{
    constructor(title, pretitle, backgroundImage){
        super(); // Whenever you extend a class you have to call parent constructor first
        this.title = title;
        this.pretitle = pretitle;
        this.backgroundImage = backgroundImage;
    }
    [...]
}

根据MDN, 在构造函数中使用时,super关键字单独出现,并且必须在使用this关键字之前使用。 super关键字也可以用于调用父对象上的函数。 您可以阅读this文章,以获得更好的主意。