Object.prototypes 内建直接规则

Ada*_*atz 3 javascript ecmascript-6 eslint

当键入检查变量以防止应用程序崩溃时,我总是使用

var hasBarProperty = foo.hasOwnProperty("bar");
Run Code Online (Sandbox Code Playgroud)

然而,我最近添加了一个新的 linting 包,并在该行上抛出了一个错误,说以下行更好

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");
Run Code Online (Sandbox Code Playgroud)

当我点击错误时,它显示了我不完全理解的解释,

https://eslint.org/docs/rules/no-prototype-builtins?fbclid=IwAR30-Z0mV40SaIPn0rPNUuyh2J3qJcsb8pE5GhNhTtZUE-sbYfLBcLNTeuM

那么为什么第二个比第一个好呢?

谢谢

T.J*_*der 6

规则告诉你使用

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");
Run Code Online (Sandbox Code Playgroud)

而不是

var hasBarProperty = foo.hasOwnProperty("bar");
Run Code Online (Sandbox Code Playgroud)

因为如果foo覆盖 hasOwnProperty ,后者可能不可靠:

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");
Run Code Online (Sandbox Code Playgroud)