Monday, August 31, 2009

hasOwnProperty to the rescue


Turns out the solution of how you can use objects as hashes and still introduce behavior in stuff like Object.prototype is to always check a method called "hasOwnProperty". This specifically tells you that a property on an object is its own and not derived from it's prototype. For example, let's say we have



Object.prototype.baz = 'baz'
function explode(divId, thingy){
for (item in thingy){
show(divId, item);
}
};




So we can't just use for ... in. But instead


function ownExplode(divId, thingy){
for (item in thingy){
if (thingy.hasOwnProperty(item))
show(divId, item);
}
};




and there we go. There is a small price to pay in terms of ugliness, but in return, we can add stuff to Object.prototype with impunity

2 comments:

  1. Adding stuff in Object ( using protoype ) could still lead to trouble when you are using third party javascript library.

    Assume that they are iterating on Array using foreach and you have added a property in Array, 3rd pary javascript library code will fail! ( ofcourse, if they have not added check for hasOwnProperty ).

    ReplyDelete
  2. you have a point there. I guess the current understanding is people ought not to use for in without using hasOwnProperty :). But if they have, yeah I can see it being an issue.

    ReplyDelete