noConstructorReturn
¥Summary
-
规则生效日期:
v1.0.0¥Rule available since:
v1.0.0 -
诊断类别:
lint/correctness/noConstructorReturn¥Diagnostic Category:
lint/correctness/noConstructorReturn -
此规则为推荐规则,默认启用。
¥This rule is recommended, which means is enabled by default.
-
此规则没有修复方案。
¥This rule doesn’t have a fix.
-
此规则的默认严重级别为 error。
¥The default severity of this rule is error.
-
来源:
¥Sources:
-
¥Same as
no-constructor-return
-
¥How to configure
{ "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; }}将此规则与单例模式结合使用
Section titled “将此规则与单例模式结合使用”¥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
Biome v2.1 中文网 - 粤ICP备13048890号