Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
58
rated 0 times [  65] [ 7]  / answers: 1 / hits: 21463  / 11 Years ago, mon, june 17, 2013, 12:00:00

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]);
};
}

More From » jquery

 Answers
8

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, but it also suffers false positives and negatives. According to MSDN.



Supported in the following document modes: Quirks, Internet Explorer 6
standards, Internet Explorer 7 standards, Internet Explorer 8
standards, Internet Explorer 9 standards, Internet Explorer 10
standards. Also supported in Windows Store apps.



JavaScript


function is(x, y) {
if (x === y) {
if (x === 0) {
return 1 / x === 1 / y;
}

return true;
}

var x1 = x,
y1 = y;

return x !== x1 && y !== y1;
}

function hasOwnProperty(object, property) {
var prototype;

return property in object && (!(property in (prototype = object.__proto__ || object.constructor.prototype)) || !is(object[property], prototype[property]));
}

function NewClass() {}
NewClass.prototype = {
a: 'there'
};

var obj = new NewClass();

if (obj.hasOwnProperty("a")) {
console.log("has property")
}

if (hasOwnProperty(obj, "a")) {
console.log("has property")
}

On JSFiddle.


[#77585] Saturday, June 15, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
beatriceisabelad

Total Points: 710
Total Questions: 107
Total Answers: 99

Location: Cayman Islands
Member since Sat, Sep 17, 2022
2 Years ago
;