Why use Object.prototype.hasOwnProperty.call(myObj, prop) instead of myObj.hasOwnProperty(prop)?

Viewed 61462

If I understand correctly, each and every object in JavaScript inherits from the Object prototype, which means that each and every object in JavaScript has access to the hasOwnProperty function through its prototype chain.

While reading RequireJS' source code, I stumbled upon this function:

function hasProp(obj, prop) {
    return hasOwn.call(obj, prop);
}

hasOwn is a reference to Object.prototype.hasOwnProperty. Is there any practical difference to writing this function as

function hasProp(obj, prop) {
    return obj.hasOwnProperty(prop);
}

And since we are at it, why do we define this function at all? Is it just a question of shortcuts and local caching of property access for (slight) performance gains, or am I missing any cases where hasOwnProperty might be used on objects which don't have this method?

6 Answers

In addition to the rest of the answers here, note that you can use the new method Object.hasOwn (supported in most browsers and soon will be supported in the rest of them) instead of Object.hasOwnProperty.call as it allows you to write a terser and shorter code.

More about Object.hasOwn - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

Browser compatibility - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility

it's much more simple with:

let foo = Object.create(null);
if (foo.bar != null) {
    console.log('object foo contains bar property in any value and 
    type, except type undefined and null');
    // bar property can exist in object foo or any object of the prototype chain
}
Related