Skip to content

noConstructorReturn

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"correctness": {
"noConstructorReturn": "error"
}
}
}
}

¥Description

禁止从 constructor 返回值。

¥Disallow returning a value from a constructor.

从类的 constructor 返回值可能是一个错误。禁止此模式可防止因不熟悉 JavaScript 或复制粘贴错误而导致的错误。

¥Returning a value from a constructor of a class is a possible error. Forbidding this pattern prevents errors resulting from unfamiliarity with JavaScript or a copy-paste error.

仅允许返回没有值,因为它是控制流语句。

¥Only returning without a value is allowed, as it’s a control flow statement.

¥Examples

¥Invalid

class A {
constructor() {
return 0;
}
}
code-block.js:3:9 lint/correctness/noConstructorReturn ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

The constructor should not return a value.

1 │ class A {
2 │ constructor() {
> 3 │ return 0;
^^^^^^^^^
4 │ }
5 │ }

The constructor is here:

1 │ class A {
> 2 │ constructor() {
^^^^^^^^^^^^^^^
> 3 │ return 0;
> 4 │ }
^
5 │ }
6 │

Returning a value from a constructor may confuse users of the class.

¥Valid

class A {
constructor() {}
}
class B {
constructor(x) {
return;
}
}

¥Using this rule in combination with the singleton pattern

有些人通过在构造函数中返回一个已存在的实例来实现 JavaScript 中的单例模式,这与此规则相冲突。

¥Some people implement the singleton pattern in JavaScript by returning an existing instance from the constructor, which would conflict with this rule.

相反,我们建议你遵循这篇博客文章中描述的建议之一:https://arendjr.nl/blog/2024/11/singletons-in-javascript/

¥Instead, we advise to follow one of the suggestions described in this blog post: https://arendjr.nl/blog/2024/11/singletons-in-javascript/

¥Related links