Since hasOwnProperty has some caveats and quirks (window / extensive use in ie8 issues / etc).
I was wondering if there is any reason to even use it, and if simply testing if a property is undefined is better justified & 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')
Just wondering if anyone has any good insight on this, I'd prefer to be using the most cross-browser friendly, and up to date methodology.
I've also seen this prototype over-write for hasOwnProperty, which works, but I'm not sold on it's 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]);
};
}
As further information to the answer given by @Pavel Gruba, and the polyfil that you supplied. To the best of my knowledge, there is no good way to polyfil
hasOwnProperty
for browsers that do not support it natively. I have seen quite a few different ones in the wild and they all produce false positives or negatives. If I have absolutely no alternative then this is what I created for my use, it also suffers false positives and negatives. According to MSDN.Javascript
On jsfiddle
The hasOwnProperty method checks that property is assigned to object directly. So, if property 'a' is in prototype hasOwnProperty will filter that.
So, hasOwnProperty is safer in many cases.
hasOwnProperty does not check for undefined values only checks if property is asigned to the object even if is undefined