Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE8 bug in for-in JavaScript statement?

I think I've found a bug in IE's (IE8) handling for the for-in javascript statement. After several hours of boiling this down to a small example, it looks like IE specifically skips any property called "toString" in a for-in loop - regardless of whether it is in a prototype or is an "Own Property" of the object.

I've placed my test code here:

function countProps(obj) {
    var c = 0;
    for (var prop in obj) {
        c++;
    }
    return c;
}

var obj = {
    toString: function() {
        return "hello";
    }
};

function test() {
    var o = "";
    var d = document.getElementById('output');

    o += "<br/>obj.hasOwnProperty('toString') == " + obj.hasOwnProperty('toString');
    o += "<br/>countProps(obj) = " + countProps(obj);
    o += "<br/>obj.toString() = " + obj.toString();

    d.innerHTML = o;
}

This should produce:

obj.hasOwnProperty('toString') == true
countProps(obj) = 1
obj.toString() = hello

but in IE, I'm getting:

obj.hasOwnProperty('toString') == true
countProps(obj) = 0
obj.toString() = hello

This special casing of any property called 'toString' is wrecking havoc with my code that tries to copy methods into a Function.prototype - my custom toString function is always skipped.

Does anyone know a work-around? Is this some sort of quirks-mode only behavior - or just a BUG?

like image 323
mckoss Avatar asked Feb 04 '23 02:02

mckoss


1 Answers

Yes, it is a bug. See this answer.

Quoting CMS:

Another well known JScript bug is the "DontEnum Bug", if an object in its scope chain contains a property that is not enumerable (has the { DontEnum } attribute), if the property is shadowed on other object, it will stay as non-enumerable, for example:

var dontEnumBug = {toString:'foo'}.propertyIsEnumerable('toString');

It will evaluate to false on IE, this causes problems when using the for-in statement, because the properties will not be visited.

like image 55
Cristian Sanchez Avatar answered Feb 05 '23 16:02

Cristian Sanchez