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?