Object.prototypes builtins directly rules

Viewed 898

When type checking variables to prevent app from crashing I always use

var hasBarProperty = foo.hasOwnProperty("bar");

However i recently added a new linting package and its throwing an error on that line saying the following line is better

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");

When I click the error it shows this explanation which I do not fully understand,

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

So why is the second one better than the first?

Thanks

1 Answers

The rule tells you to use

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");

rather than

var hasBarProperty = foo.hasOwnProperty("bar");

because if foo has overridden hasOwnProperty, the latter may not be reliable:

var foo = {
  hasOwnProperty: function() {
    return true;
  }
};
console.log(Object.prototype.hasOwnProperty.call(foo, "bar")); // false
console.log(foo.hasOwnProperty("bar"));                        // true

Related