A brief discussion on the modifiable problem of JavaScript function parameters
- 2020-03-30 00:43:54
- OfStack
A pen question is the result of thinking that normally no one would change the parameter values inside a function. Just for discussion here, there are three ways to modify.
1. Directly modify the parameters of the function declaration
function f1(a) {
alert(a);
a = 1;//Modify parameter a
alert(1 === a);
alert(1 === arguments[0]);
}
f1(10);
Function f1 defines parameter a, when called, pass parameter 10, pop up 10 first, change a to 1, pop up true twice, a and arguments[0] are 1.
2, via the arguments object inside the function
function f2(a) {
alert(a);
arguments[0] = 1;//Modify the arguments
alert(1 === a);
alert(1 === arguments[0]);
}
The effect is the same as the function f1.
3. The local variable declared inside the function has the same name as the parameter
function f3(a) {
alert(a);
var a = 1;//Declare the local variable a and assign it a value of 1
alert(1 === a);
alert(arguments[0]);
}
f3(10);
The function f3 defines the parameter a. The function internally declares the local variable a and assigns a value of 1, but here the a is still the parameter a, which can be proved by the argument [0] that pops up at the end being changed to 1.
4. If you just declare the local variable a and don't assign a value, that's different
function f3(a) {
var a;//Declaration only, no assignment
alert(a);
alert(arguments[0]);
}
f3(10);
Instead of undefined, all of the 10's that pop up.