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

问题描述 投票:1回答:2

此问题已经在这里有了答案:

我的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。我在做什么错?

javascript ecmascript-6 es6-class
2个回答
2
投票

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

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
投票

只需添加此行

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文章,以获得更好的主意。

© www.soinside.com 2019 - 2024. All rights reserved.