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 :)

Comments 6

  1. Bill Zeller wrote:

    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)

    Posted 08 Jan 2009 at 9:32 pm
  2. Bill Zeller wrote:

    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)

    Posted 08 Jan 2009 at 9:36 pm
  3. Gareth Heyes wrote:

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

    Posted 08 Jan 2009 at 9:59 pm
  4. Ron wrote:

    so there’s no way to do this?

    Posted 09 Jan 2009 at 8:54 am
  5. Gareth Heyes wrote:

    Nope doesn’t look like it :(

    Posted 09 Jan 2009 at 10:12 am
  6. Acidus wrote:

    Hurray! Otherwise I would had to update Ajax Security.

    Posted 09 Jan 2009 at 2:12 pm

Post a Comment

Your email is never published nor shared. Required fields are marked *

Comment spam protected by SpamBam