Calling the Array constructor in IE

I had a conversation a while ago on email with Billy Hoffman about how in IE the Array constructor wasn’t called when using [] to create arrays. The question is, was he right? Technically yes but actually no :)

You see Arrays in JScript are actually objects and not arrays, so trying to overwrite the Array constructor will have no effect. However using the Object constructor does. I found this while hacking away in JSON to create my Twitter POC.

The is a strange quirk which although it technically is the same code it results in different behaviour. Take the following example:-

function Object() {
 alert(arguments[0]);
}
([1,2,3]);

That doesn’t work but…look at this example:-

var Object = function() {
 alert(arguments[0]);
}
([1,2,3]);

It works! Yay! Strange but true. Don’t ask how I found this but it was either by fuzzing, playing around in Hackvertor or pure luck :)

6 Responses to “Calling the Array constructor in IE”

  1. Bill Zeller writes:

    Are you sure?

    var Object = function() {
    alert(arguments[0]);
    }
    ([1,2,3]);

    runs the code

    function() {alert(arguments[0]);}([1,2,3]);

    and sets the result (undefined) equal to Object. (Try calling new Object() after doing this). For example:

    var Object = function() {
    alert(arguments[0]);
    return 5;
    }
    ([1,2,3]);

    alert(Object);

    Of course, this does still work if you do:

    var Object = function() {
    alert(arguments[0]);
    };
    ([1,2,3]);

    :-) (notice the semicolon after the function)

  2. Bill Zeller writes:

    Actually I may have spoken too soon. I can no longer get:

    var Object = function() {
    alert(arguments[0]);
    };
    ([1,2,3]);

    to work in Firefox 3.0.5 (calling new Object([1,2,3]) works though)

  3. Gareth Heyes writes:

    Bill your right, I’m a dumbass. Doh!

  4. Ron writes:

    so there’s no way to do this?

  5. Gareth Heyes writes:

    Nope doesn’t look like it :(

  6. Acidus writes:

    Hurray! Otherwise I would had to update Ajax Security.