Given the following code:
class ExampleClass {
someMethod(x) {
arguments[0] = 100;
console.log(arguments[0]);
return x;
}
}
let example = new ExampleClass();
console.log([example.someMethod("5")]);
function someFunction(x) {
arguments[0] = 100;
console.log(arguments[0]);
return x;
}
console.log([someFunction("5")]);
I would expect the output to be:
100
[100]
100
[100]
However in the class example this doesn't seem to work and instead it changes arguments[0]
to 100 like it should but x remains unchanged.
So instead the output is:
100
["5"]
100
[100]
Is there some kind of workaround or will arguments
never affect the parameters inside a class method?
CodePudding user response:
From the MDN documentation on arguments
In strict-mode code, the
arguments
object behaves the same whether or not a function is passed rest, default, or destructured parameters. That is, assigning new values to variables in the body of the function will not affect thearguments
object. Nor will assigning new variables to thearguments
object affect the value of variables.
And from the documentation of strict mode:
All parts of ECMAScript classes are strict mode code, including both class declarations and class expressions — and so also including all parts of class bodies.
So the assignment to arguments[0]
has no effect on the x
parameter because this is in a class, which is in strict mode.
arguments
is generally considered an obsolete feature in EcmaScript 6. This was traditionally used to implement rest and default parameters, which now have explicit syntax in parameter lists. Since class definitions are ES6, you should use the more modern syntax with them.