Call and apply
The call and apply methods can invoke functions through the function name. There are two parameters
The call () method has the same effect as the Apply () method, except that they differ only in the way they receive parameters.
"Call"
Invokes one method of an object, replacing the current object with another object.
The call () method is the most similar method to the Classic object impersonation method. His first argument is used as the this object, and the other parameters are passed directly to the function itself.
For call, the first parameter is the context object, and the second argument is a different function parameter.
Call is passed through a parameter list, others are not different from apply
"Apply"
Applies one method of an object, replacing the current object with another object.
For apply, there are two parameters, the first is the context of the call, the second is the parameter array, you can directly transfer the argument in.
"The use and distinction of call and apply"
functionsum (num1,num2) {returnnum1+num2;}functionCallSum1 (num1,num2) {//Use the SUM function to complete a call, and the arguments to the function are the parameters of the function callSum1 //the second parameter of apply represents a set of parameter arrays returnSum.apply ( This, argument);}functioncallSum2 (num1,num2) {//The second argument is an array returnSum.apply ( This, [num1,num2]); }functioncallSum3 (num1,num2) {//pass through the parameter list returnSum.call ( This, num1,num2);}
It is convenient to use the Apply () method if it is passed directly to the argument object, or if it is an array that is received first in the containing function, otherwise it is more appropriate to choose call (). If you do not pass parameters to the function, you can use whichever method.
The real power of call () and apply () is the ability to extend the scope in which functions are run. The biggest benefit of using call () (or apply ()) to extend the scope is that the object does not need to have any coupling with the method.
JavaScript (9)--call and apply