In depth understanding of Javascript dynamic method invocation and parameter modification
- 2020-03-30 00:45:50
- OfStack
The passed parameters can be modified in the function in Javascript, as shown below
function func1(name) {
name = 'lily';
alert(name);
}
func1('jack');//Output lily
Let's do another example
function fun1(n) {
this.name = n;
}
function fun2(name) {
fun1.call(this,'lily');
alert(name);
}
fun2("jack");//Output "jack"
The fun1 function tried to change the argument to "lily" when fun2 was called, but failed. The popup is still "jack". Think about why?
In fact, fun1 has the ability to change the parameters of the call to fun2, using the caller property
function fun1() {
arguments.callee.caller.arguments[0] = 'lily';
}
function fun2(name) {
fun1.call(this,name);
alert(name);
}
fun2("jack");//Output "lily"
As you can see, the outer function is visible and modifiable to the call stack of the inner function.