为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

牧羊人nacy 2021-12-02 15:30:22
我的 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 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

您需要super()在您的子类中调用,正如MDN 解释的那样:“在构造函数中使用时, super 关键字单独出现并且必须在使用this 关键字之前使用。”


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)


查看完整回答
反对 回复 2021-12-02
?
GCT1015

TA贡献1827条经验 获得超4个赞

只需添加这一行


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 关键字还可用于调用父对象上的函数。你可以阅读这篇文章,以获得更好的想法。


查看完整回答
反对 回复 2021-12-02
  • 2 回答
  • 0 关注
  • 721 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信