Wednesday, May 28, 2008

Check for extended properties inside for..in loops

Problem:
Running a for..in loop on an object returns all enumerated properties of that object, including any methods/properties added using the prototype property. In the age of ubiquitous JavaScript libraries such as Prototype that does extend built-in objects, not accounting for those extended properties could break your code.

Solution:
it's essential to check for those extended methods and properties whenever the for..in loop is used. This is done by using the hasOwnProperty() Object method.
for (var elem in FunObject) {
if (FunObject.hasOwnProperty()) {
// proceed with code
}
}

No comments:

Blog Archive