CLARIFICATION to moderator
As some moderators are a whee bit quick when scanning questions, I have to underline that I am not asking why to use Object.prototype.hasOwnProperty.call instead of myObject.hasOwnProperty. The devil is in the details.
The ESLint rule no-prototype-builtins forbids the use of built-ins coming from the Object prototype. It's there to provide you against code such as this:
function serverMethodToParseClientInput(json){
const o = JSON.parse(json);
if (o.hasOwnProperty("foo")) {
doSomethingMeaningful();
}
}
const stringFromClient = "{\"hasOwnProperty\":1, \"reason\": \"Crash your system\"}";
serverMethodToParseClientInput(stringFromClient);
Trying to call the method on objects created with null as their prototype will also fail, which I think is an even more reasonable thing to guard against. Example: const o = Object.create(null);.
Instead of obj.hasOwnProperty(field), you are supposed to use Object.prototype.hasOwnProperty.call(obj, field). I don't really see the difference between this and Object.hasOwnProperty.call(obj, field). Granted, Object is not its own prototype, so there is a difference of sorts, but since you can overwrite the props on either object, there isn't really much of a safeguard here, IMHO.
So I'm wondering if there is any point in reaching for the prototype of Object when Object will do?
Using Object.hasOwnProperty is weird because it makes it seem like you are using a static method like Object.assign().
It still works because if a property is not found on Object, it falls back to Function.prototype object. And, this object inherits from Object.prototype. So, if you have a custom implementation for Function.prototype.hasOwnProperty, then Object.hasOwnProperty will use that implementation instead of Object.prototype.hasOwnProperty
console.log( Object.hasOwnProperty === Object.prototype.hasOwnProperty ) // true
console.log( Object.getPrototypeOf(Object) === Function.prototype ) // true
console.log( Object.getPrototypeOf(Function.prototype) === Object.prototype ) // true
Function.prototype.hasOwnProperty = _ => 'custom implementaion in Function.prototype'
const obj = { prop: 10 }
console.log(Object.hasOwnProperty.call(obj, 'prop')) // custom implementaion
console.log(Object.prototype.hasOwnProperty.call(obj, 'prop')) // true
Note: The difference between Object.prototype.hasOwnProperty.call(myObj, prop) and myObj.hasOwnProperty(prop) is explained here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With