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.
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
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.
hasOwnProperty() is faster. I realize there are other ways to make the loops faster, like storing lengths in variables.
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.
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);
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