1, the difference between apply and call and use
The same point : 2 is a method of the function prototype, so the caller must be a function, and the 1th argument is the object. The effect is to replace the current object with another object, which is the first argument you pass. Typically used to change the direction of this in a called function. If you do not pass an object or pass in NULL, the default object is window.
Differences : The 2nd parameter, which is the parameter of the called function, is the difference that apply requires that all arguments of the function be passed in an array.
How to use :
Fun.call (thisarg[, arg1[, arg2[, ...]) Fun.apply (Thisarg, [arg1,arg2,... ArgN])
Fun.call (this, arg1,arg2,arg3) = = Fun.apply (this, arguments) = = This.fun (arg1, arg2, Arg3)
<script type= "Text/javascript" > function func (arg1, arg2) { Console.log (this) if (arg1) { Console.log (arg1); } if (arg2) { console.log (arg2); } } var obj = {name: "DSFSD"} console.log ('-------use of apply-------start '); Func.apply (); Func.apply (null); Func.apply (obj, ["Apply-arg1", "apply-arg2"]); Console.log ('-------use of apply-------end '); Console.log ('-------the use of call-------start '); Func.call () func.call (null); Func.call (obj, "call-arg1", "call-arg2"); Console.log ('-------Call's use-------end ');</script>
Operating effect :
2, Callee
First introduce the next arguments object, he can only be used inside the JS function, is a special object, like an array but not an array. You can get the parameter value of the function by using an index. The callee is a property of the arguments object that returns the current function object, which is the current one, so it is often seen in recursive functions Arguments.callee, which can be followed by parameters of the function.
This is a dead loop.
function func (arg1) {
Console.log (Arguments.callee);
Console.log (Arguments.callee (10));
}
Func (10);
3, caller
The literal meaning is the caller of the current function, that is, the person who called the current function. Returns the caller of the current function if the function is a top-level call that returns NULL. The method of use is: the function name. Caller, which can be followed by the arguments of the functions.
function func (arg1) { console.log (func.caller); Func.caller (123456);} function Func2 (arg1) { if (arg1) { console.log (arg1); Console.log (Func2.caller); } else { console.log (func2.caller); Func (); }} Func2 ();
The 1th execution of Func2 is a top-level call that returns NULL. Then execute func, print out the Func caller Func2, then execute FUNC2 (with parameters), print out the parameter value and FUNC2 's caller func function.
The difference between apply, call, callee and caller in JS