Since hasOwnProperty has some caveats and quirks (window / extensive use in Internet Explorer 8 issues, etc.):
Is there any reason to even use it? If simply testing if a property is undefined, is it better justified and more simplistic?
For example:
var obj = { a : 'here' };
if (obj.hasOwnProperty('a')) { /* do something */ }
if (obj.a !== undefined) { /* do something */ }
// Or maybe (typeof (obj.a) !== 'undefined')
I'd prefer to be using the most cross-browser friendly, and up to date methodology.
I've also seen this prototype overwritten for hasOwnProperty, which works, but I'm not sold on its usefulness...
if (!Object.prototype.hasOwnProperty) {
Object.prototype.hasOwnProperty = function(prop) {
var proto = this.__proto__ || this.constructor.prototype;
return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]);
};
}
hasOwnProperty
is guaranteed to produce false positives or negatives – Biafra.hasOwnProperty
is a lot slower than any other way of testing property existence (that was surprising for me TBH). – Islamite.hasOwnProperty
andin
have very different meaning. Quoting Mozilla documentation:"obj.hasOwnProperty(prop)" used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.
– Gertiegertrud