Calling the Array constructor in IE
Thursday, 8 January 2009
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 π
No. 1 — January 8th, 2009 at 9:32 pm
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)
No. 2 — January 8th, 2009 at 9:36 pm
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)
No. 3 — January 8th, 2009 at 9:59 pm
Bill your right, I’m a dumbass. Doh!
No. 4 — January 9th, 2009 at 8:54 am
so there’s no way to do this?
No. 5 — January 9th, 2009 at 10:12 am
Nope doesn’t look like it π
No. 6 — January 9th, 2009 at 2:12 pm
Hurray! Otherwise I would had to update Ajax Security.