April 14, 2006

Variable Names vs. Argument Names in Spidermonkey

Variable Names vs. Argument Names in Spidermonkey

Spidermonkey, the JavaScript engine at the heart of Firefox and other Gecko browsers, treats variables declared inline and those declared in the argument list differently. I noticed this quirk a little while ago, and stumbled upon it again recently. To demonstrate, first an example.

function foo (arg1) {
 alert(arguments[0]);
 arg1 = 'bar';
 alert(arguments[0]);
}

foo('test');

In this example the first alert box says 'test', however the second alert box says 'bar'. This might not be what you expect and certainly isn't what I expected. The variable arg1 is not just a reference to the object that was passed in. Using the assigment operator doesn't just change the reference contained in the variable arg1 to point to another object, it also changes the arguments array.

What I expected to happen, and what happens in other browsers would be more like this:

function foo () {
 var arg1 = arguments[0];
 alert(arguments[0]);
 arg1 = 'bar';
 alert(arguments[0]);
}

foo('test');

With both the first and second alert boxes reading 'test' and the variable simply being a reference, independant of the reference in the arguments array.

Odd.

0 Comments:

Post a Comment

<< Home