We can regard call and apply as methods of an object. The first real parameter of call and apply is the parent object of the function to be called indirectly by calling methods, it is the call context and obtains reference to it through this in the function body.
For example, if you want to call function f using the method of object o, you can use the call and apply methods as follows:
The Code is as follows:
F. call (o );
F. apply (o );
You can understand the following code:
The Code is as follows:
O. m = f; // temporary Method for storing f as o
O. m (); // call this temporary Method
Delete o. m; // delete this temporary Method
Here is an example.
The Code is as follows:
Function testFun (){
Return this. a + this. B;
}
Var o = {a: 1, B: 2 };
TestFun. call (o); // 3
TestFun. apply (o); // 3
The result of the above code execution is 3, which can be understood as return o. a + o. B.
Consider one question: What if the first real parameter of the call and apply methods is null or undefined? Let's take a look at the following example:
The Code is as follows:
Var a = 10, B = 20;
Function testFun (){
Return this. a + this. B;
}
TestFun. call ();
TestFun. apply ();
The execution result of the above Code is 30. This is because if the first real parameter of call and apply is null or undefined, it will be replaced by a global object.
What is the difference between the call and apply methods?
For the call method, all the real parameters after the first call context real parameters are the values of the functions to be called. For example, you can use the following code to call function f in the form of object o and input two parameters:
The Code is as follows:
F. call (o, 1, 2 );
The apply method puts all the real parameters after the first real parameter into a number group,
The Code is as follows:
F. apply (o, [1, 2]);
Here is an example.
The Code is as follows:
Function testFun (x, y ){
Return this. a + this. B + x + y;
}
Var o = {a: 1, B: 2 };
TestFun. call (o, 10, 20 );
TestFun. apply (o, [10, 20]);
The execution result of the above Code is 33, which can be understood as return o. a + o. B + 10 + 20.