Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between obj.hasOwnProperty() & Object.prototype.hasOwnProperty.call()?

Tags:

javascript

Code one:

obj.hasOwnProperty(prop);

Code Two:

const hasOwnProperty = Object.prototype;
hasOwnProperty.call(obj, prop); 

I always use the first coding style, but I saw several times about the second coding style in some JS books or github projects. I want to know it's just a habit or really a better way to write my js code. Thanks.

like image 385
ShanshanXu Avatar asked Jun 04 '20 03:06

ShanshanXu


People also ask

What does hasOwnProperty method do?

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

Should you use hasOwnProperty?

If the question is slightly rephrased to: "Is the use of hasOwnProperty() required if I have full control over the JS script, where it's used and everything in its or parent scopes?" Then no, you don't need to use the hasOwnProperty() . But the full control over the environment is not something you should count on.

Is hasOwnProperty fast?

hasOwnProperty() is faster. I realize there are other ways to make the loops faster, like storing lengths in variables.

What is the use of hasOwnProperty in JavaScript?

The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being it's own.


1 Answers

If the obj is not tampered with, there is relatively little difference. But all sorts of stuff can get in the way if you rely on obj containing the prototype function as you expect it to work (potentially even by accident). This is why you'll often see libraries make calls to the prototype methods directly instead of relying on them being in tact on the individual objects.

Consider this case:

const prop = 'test';

obj = {test: 'example'};
console.log({
 'version': 'no tampering!',
 'obj.hasOwnProperty': obj.hasOwnProperty(prop),
 'Object.prototype.hasOwnProperty': Object.prototype.hasOwnProperty.call(obj, prop)
});

// someone does something you don't expect with obj
obj.hasOwnProperty = () => false;
// NOTE: This at least is a function, there is nothing to stop me from setting it to something that would BREAK the function call...
// E.g. obj.hasOwnProperty = 42;

console.log({
 'version': 'some tampering!',
 'obj.hasOwnProperty': obj.hasOwnProperty(prop),
 'Object.prototype.hasOwnProperty': Object.prototype.hasOwnProperty.call(obj, prop)
});

Or, what if obj is an object that does not inherit the Object prototype?

const obj =  Object.create(null);

console.log(obj.hasOwnProperty);
like image 75
Chase Avatar answered Oct 19 '22 02:10

Chase