Index

constructor-super

要求在构造函数中调用 super()

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

派生类的构造函数必须调用 super()。 非派生类的构造函数不得调用 super()。 如果不遵守这一点,JavaScript 引擎将抛出运行时错误。

🌐 Constructors of derived classes must call super(). Constructors of non derived classes must not call super(). If this is not observed, the JavaScript engine will raise a runtime error.

此规则检查是否存在有效的 super() 调用。

🌐 This rule checks whether or not there is a valid super() call.

规则详情

🌐 Rule Details

此规则旨在标记无效或缺失的 super() 调用。

🌐 This rule is aimed to flag invalid/missing super() calls.

这是一个语法错误,因为类中没有 extends 子句:

🌐 This is a syntax error because there is no extends clause in the class:

class A {
    constructor() {
        super();
    }
}

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint constructor-super: "error"*/

class A extends B {
    constructor() { }  // Would throw a ReferenceError.
}

// Classes which inherits from a non constructor are always problems.
class C extends null {
    constructor() {
        super();  // Would throw a TypeError.
    }
}

class D extends null {
    constructor() { }  // Would throw a ReferenceError.
}

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint constructor-super: "error"*/

class A {
    constructor() { }
}

class B extends C {
    constructor() {
        super();
    }
}

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

何时不使用

🌐 When Not To Use It

如果你不想在构造函数中收到关于无效/缺失 super() 调用的通知,你可以安全地禁用此规则。

🌐 If you don’t want to be notified about invalid/missing super() callings in constructors, you can safely disable this rule.

由 TypeScript 处理

使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。

版本

此规则是在 ESLint v0.24.0 中引入。

资源