Is this legal? And does it work in all browsers?
function func1(a, b, c) {
//b == 2 here
change_em(arguments);
//b should equal 3 here
}
function change_em(args) {
args[0] = 6;
args[1]++;
args[2] = [];
}
func1('foo', 2);
If you are wondering, I need to adjust the arguments in a function. A macro would be perfect, except javascript doesn’t have one. Doing it properly, i.e. passing the variables to a function, then returning them in an object, and then extracting them in the caller would be almost as much code as just copy/pasting the adjuster function.
It is valid under EcmaScript 3 and EcmaScript 5 non-strict, but it is not valid under EcmaScript 5 strict mode. It works in all modern browsers and most old ones. It should not work in strict mode such as when run in Firefox 5 with a
"use strict"directive.From the EcmaScript 5 spec section 10.6.11.c.ii
Basically, the
argumentsobject gets a setter for each index so that assigning toarguments[i]changes the value of the named parameter at positioni. There is language in the spec which makes it work vice-versa.This should work in non-strict mode in any interpreter
But if you run the above on Firefox 5 with a use strict directive you get different behavior: