为什么使用 Object.prototype.hasOwnProperty.call(myObj, prop) 而不是 myObj.hasOwnProperty(prop)?
标题太长了,掘金貌似不能支持这么长的标题,就只能把标题放在正文了。
复制代码
这是我昨天在阅读 Airbnb 的 Javascript 风格指南的时候,阅读到其中有一条:
Do not call Object.prototype methods directly, such as hasOwnProperty, propertyIsEnumerable, and isPrototypeOf.
// bad console.log(object.hasOwnProperty(key)); // good console.log(Object.prototype.hasOwnProperty.call(object, key)); // best const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope. /* or */ import has from 'has'; // https://www.npmjs.com/package/has // ... console.log(has.call(object, key)); 复制代码
当时在想为什么呢,第一时间想到的就是:
这个实例有可能重写了 hasOwnProperty 等方法,当然这也是最主要的原因了。
然后还提到说:
如果使用 Object.create(null) 创建的对象是没有prototype的,所以是没有任何方法的,这种情况下,调用上述方法只会得到 undefined
。
这显然不是想要的结果,所以,使用 Object.prototype.hasOwnProperty.call(myObj, prop),可以确保调用到正确的方法,并且得到?正确的结果。