Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical differences of Object.hasOwnProperty vs Object.prototype.hasOwnProperty

Tags:

javascript

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?

like image 846
oligofren Avatar asked Feb 28 '26 07:02

oligofren


1 Answers

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

like image 60
adiga Avatar answered Mar 01 '26 20:03

adiga