使用未完全初始化的对象¶
ID: js/incomplete-object-initialization
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- correctness
- language-features
Query suites:
- javascript-security-and-quality.qls
如果一个类扩展了另一个类,则其构造函数需要在引用this
或通过super
访问属性之前调用 super 构造函数。否则会导致运行时错误。
建议¶
插入 super 构造函数调用。
示例¶
在以下示例中,类A
扩展了类B
,但其构造函数在调用 super 构造函数之前就对this.x
进行了赋值,这会导致运行时错误。
class A extends B {
constructor() { this.x = 42; }
}
为了防止错误,应该插入 super 构造函数调用。
class A extends B {
constructor() { super(); this.x = 42; }
}
参考资料¶
Mozilla 开发者网络:使用 extends 进行子类化.