Fun with browsers: for in loop

Tobie Langel is having fun with for loops in JavaScript and wrote about how they are broken in Safari. This is the classic issue of looping through properties of an object, and getting all properties:
JAVASCRIPT:
  1. var Person = function(name) {
  2. this.name = name;
  3. };
  4. Person.prototype.name = 'anonymous';
  5. var john = new Person('John');
  6. var result = '';
  7. for (var property in john)
  8. result += property + ': ' + john[property] + '\n';
Safari will display two name properties (one for the object itself, and one for the prototype). You need to guard this via hasOwnProperty:
JAVASCRIPT:
  1. for (var property in john)
  2. if(john.hasOwnProperty(property))
  3. result += property + ': ' + john[property] + '\n';
This doesn't work in Safari.current, but is fixed in WebKit.

Fun with browsers: for in loop

Tobie Langel is having fun with for loops in JavaScript and wrote about how they are broken in Safari.

This is the classic issue of looping through properties of an object, and getting all properties:

JAVASCRIPT:
  1.  
  2. var Person = function(name) {
  3.   this.name = name;
  4. };
  5.  
  6. Person.prototype.name = 'anonymous';
  7.  
  8. var john = new Person('John');
  9.  
  10. var result = '';
  11. for (var property in john)
  12.   result += property + ': ' + john[property] + '\n';
  13.  

Safari will display two name properties (one for the object itself, and one for the prototype).

You need to guard this via hasOwnProperty:

JAVASCRIPT:
  1.  
  2. for (var property in john)
  3.   if(john.hasOwnProperty(property))
  4.     result += property + ': ' + john[property] + '\n';
  5.  

This doesn't work in Safari.current, but is fixed in WebKit.


January 29th, 2007

Tagged View

Tags Similar

Posts Fresh +

Categories View