A lot of Javascript developers automatically reach for hasOwnProperty
when looping over an object with for...in; case in point something I read on reddit recently:
for (var k in this.generalKeyHandling) {
if (this.generalKeyHandling.hasOwnProperty(k) && this.down.indexOf(k) > -1) {
// etc.
The object however had just been defined in an immediately preceding literal, therefore it would not have any inherited properties, which is the point of using hasOwnProperty
. Not only is using it in this case therefore unnecessary, but a JSPerf seems to indicate it could be up to 10 times slower.
If object (literals) you define can somehow get hijacked such that they have inhertited properties by the time you want to iterate over them, you have bigger problems that using hasOwnProperty
merely masks. So, when thinking about using it, to quote some advice from a lost episode of the Andy Griffith show: "Aunt Bea, I gotta cookin' tip for ya: DON'T!"
Top comments (6)
hasOwnPropery
is meant as a way to ensure that you are only iterating over values that belong to the object you are checking the property against. Meaning that you won't use cpu to process information on properties that live on the parent of the object you inherited from.Also, I'm not sure what you mean by "hijacked"? I'm not sure how that plays into your argument about the object growing or not to use
hasOwnPropery
?Sorry man, I'm still not understanding the message you are trying to convey. Is it that when looping through object literals that don't inherit from other objects, it's not necessary to include the
hasOwnProperty
check?hasOwnPropery
is a great way to prevent you from looping though the object prototype. Sorry, but I can't see any reason not to.Where I agree with you, it's that you perform an unnecessary check. The best IMO, it not to avoid
hasOwnPropery
, but to prefer other loops likefor( ... of ... )
orObject.keys().forEach()
.Usually I use
Also you can
seal
and/orfreeze
objects if that's the desired effect.In this regard, any idea how hasOwnPropery compares to Object.keys?