"Cannot access uninitialized variable." 在 class 构造函数中
"Cannot access uninitialized variable." in class constructor
我的 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
。我做错了什么?
您需要在 child class 中调用 super()
,如 MDN explains: "When used in a constructor, the super keyword appears alone and must be used before the this keyword is used."
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)
只需添加这一行
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 文章,以获得更好的想法。
我的 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
。我做错了什么?
您需要在 child class 中调用 super()
,如 MDN explains: "When used in a constructor, the super keyword appears alone and must be used before the this keyword is used."
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)
只需添加这一行
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 文章,以获得更好的想法。