Index

no-obj-calls

不允许将全局对象属性作为函数调用

Recommended

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

ECMAScript 提供了几个打算按原样使用的全局对象。其中一些对象由于其首字母大写(例如 MathJSONTemporal)看起来像构造函数,但如果你尝试以函数方式执行它们,会抛出错误。

🌐 ECMAScript provides several global objects that are intended to be used as-is. Some of these objects look as if they could be constructors due to their capitalization (such as Math, JSON, and Temporal) but will throw an error if you try to execute them as functions.

ECMAScript 5 规范 明确指出,MathJSON 都不能被调用:

🌐 The ECMAScript 5 specification makes it clear that both Math and JSON cannot be invoked:

Math 对象没有 [[Call]] 内部属性;无法将 Math 对象作为函数调用。

ECMAScript 2015规范 明确指出 Reflect 不能被调用:

🌐 The ECMAScript 2015 specification makes it clear that Reflect cannot be invoked:

Reflect 对象也没有 [[Call]] 内部方法;无法将 Reflect 对象作为函数调用。

ECMAScript 2017规范明确指出Atomics不能被调用:

🌐 The ECMAScript 2017 specification makes it clear that Atomics cannot be invoked:

Atomics 对象没有 [[Call]] 内部方法;无法将 Atomics 对象作为函数调用。

ECMAScript 国际化 API 规范 明确指出 Intl 不能被调用:

🌐 The ECMAScript Internationalization API Specification makes it clear that Intl cannot be invoked:

Intl 对象没有 [[Call]] 内部方法;无法将 Intl 对象作为函数调用。

时间提案规范 明确指出 Temporal 不能被调用:

🌐 The Temporal proposal specification makes it clear that Temporal cannot be invoked:

Temporal 对象没有 [[Call]] 内部方法;它不能作为函数被调用。

规则详情

🌐 Rule Details

此规则不允许将 MathJSONReflectAtomicsIntlTemporal 对象作为函数调用。

🌐 This rule disallows calling the Math, JSON, Reflect, Atomics, Intl, and Temporal objects as functions.

此规则还禁止将这些对象用作 new 操作符的构造函数。

🌐 This rule also disallows using these objects as constructors with the new operator.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint no-obj-calls: "error"*/

const math = Math();

const newMath = new Math();

const json = JSON();

const newJSON = new JSON();

const reflect = Reflect();

const newReflect = new Reflect();

const atomics = Atomics();

const newAtomics = new Atomics();

const intl = Intl();

const newIntl = new Intl();

const temporal = Temporal();

const newTemporal = new Temporal();

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

🌐 Examples of correct code for this rule:

在线运行
/*eslint no-obj-calls: "error"*/

function area(r) {
    return Math.PI * r * r;
}

const object = JSON.parse("{}");

const value = Reflect.get({ x: 1, y: 2 }, "x");

const first = Atomics.load(foo, 0);

const segmenterFr = new Intl.Segmenter("fr", { granularity: "word" });

const instant = Temporal.Now.instant();

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

由 TypeScript 处理

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

版本

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

进阶读物

资源