Monday, January 29th, 2007
Fun with browsers: for in loop
<>p>Tobie Langel is having fun withfor 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:
-
-
var Person = function(name) {
-
this.name = name;
-
};
-
-
Person.prototype.name = 'anonymous';
-
-
var john = new Person('John');
-
-
var result = '';
-
for (var property in john)
-
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:
-
-
for (var property in john)
-
if(john.hasOwnProperty(property))
-
result += property + ': ' + john[property] + 'n';
-
This doesn't work in Safari.current, but is fixed in WebKit.








Actually, you don’t need
hasOwnPropertyfor it to work in WebKit.I am confused, does this break safari, does it work in safari, whats the problem and how to fix it??? One note, in IE (not sure abut the others) it will ignore the method toString() in any object when doing a for-in loop. I use Object.extend() with Prototype and noticed it wasnt making the copy of toString(). somehting to keep in mind.
I read the article. Shame on Buggy Safari. Safari has bent over backwards to be compatible with IE and in the process is compatible with Nothing. It is always the brwoser to fail in my code. I dislike it.
I think that this may simply be a matter of opinion. Safari was the first browser to successfully render the ACID2 CSS test, which proves it was (at the time) the only browser to properly implement the CSS spec. I have very few problems developing for Safari. I think you simply need to avoid certain browser-compatibility pitfalls (which will never go away) as is the case with all browsers. On the sunny side, it’s good to see the WebKit community so active in fixing these problems. I have never seen IE or Moz dev move so quickly.
Just ignore it. There is a firefox for Mac Users. It’s enough work to condescend to the mass of IE users ;)
Wow… some people still have the attitude of “Just ignore it”… what a cop-out for lazy developers. Developing for all browsers is not hard, and is a must. If you think it is too big of a pain in the butt… then you need a new job… cuz that ain’t going away anytime soon!
Passing ACID has nothing to do with JS. Ironically, Safari didn’t even support hasOwnProperty until 2.0, which is a very core JS function. I do not like coding for Safari at all, but unfortunately, more of us can’t “just ignore it”. I would much rather code for IE than Safari. But hopefully you are right Steve, that WebKit quick adoption of ACID signals that they are and will continue to move quickly and things will improve on the JS side for Safari.