no-obj-calls
不允许将全局对象属性作为函数调用
在 配置文件 中使用来自 @eslint/js
的 recommended
配置可以启用此规则
ECMAScript 提供了几个旨在按原样使用的全局对象。其中一些对象看起来好像是构造函数,因为它们的大小写(例如 Math
和 JSON
),但如果你尝试将它们作为函数执行,则会引发错误。
¥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 their capitalization (such as Math
and JSON
) but will throw an error if you try to execute them as functions.
ECMAScript 5 规范 明确表示不能调用 Math
和 JSON
:
¥The ECMAScript 5 specification makes it clear that both Math
and JSON
cannot be invoked:
Math 对象没有
[[Call]]
内部属性;无法将 Math 对象作为函数调用。¥The Math object does not have a
[[Call]]
internal property; it is not possible to invoke the Math object as a function.
ECMAScript 2015 规范 明确表示不能调用 Reflect
:
¥The ECMAScript 2015 specification makes it clear that Reflect
cannot be invoked:
Reflect 对象也没有
[[Call]]
内部方法;不可能将 Reflect 对象作为函数调用。¥The Reflect object also does not have a
[[Call]]
internal method; it is not possible to invoke the Reflect object as a function.
ECMAScript 2017 规范 明确表示不能调用 Atomics
:
¥The ECMAScript 2017 specification makes it clear that Atomics
cannot be invoked:
Atomics 对象没有
[[Call]]
内部方法;不可能将 Atomics 对象作为函数调用。¥The Atomics object does not have a
[[Call]]
internal method; it is not possible to invoke the Atomics object as a function.
并且 ECMAScript 国际化 API 规范 明确表示不能调用 Intl
:
¥And the ECMAScript Internationalization API Specification makes it clear that Intl
cannot be invoked:
Intl 对象没有
[[Call]]
内部方法;不可能将 Intl 对象作为函数调用。¥The Intl object does not have a
[[Call]]
internal method; it is not possible to invoke the Intl object as a function.
规则详情
¥Rule Details
此规则不允许将 Math
、JSON
、Reflect
、Atomics
和 Intl
对象作为函数调用。
¥This rule disallows calling the Math
, JSON
, Reflect
, Atomics
and Intl
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"*/
var math = Math();
var newMath = new Math();
var json = JSON();
var newJSON = new JSON();
var reflect = Reflect();
var newReflect = new Reflect();
var atomics = Atomics();
var newAtomics = new Atomics();
var intl = Intl();
var newIntl = new Intl();
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-obj-calls: "error"*/
function area(r) {
return Math.PI * r * r;
}
var object = JSON.parse("{}");
var value = Reflect.get({ x: 1, y: 2 }, "x");
var first = Atomics.load(foo, 0);
var segmenterFr = new Intl.Segmenter("fr", { granularity: "word" });
由 TypeScript 处理
使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。
版本
此规则是在 ESLint v0.0.9 中引入。