A. Each function contains two non-inherited methods: Apply () and call ().
B. The purpose of both methods is to invoke the function in a specific scope, which is actually equal to the value of the this object in the body of the function.
C. The Apply () method receives two parameters: one is the scope in which the function is run, and the other is the parameter array. Where the second argument can be an instance of an array, or it can be an arguments object.
D. The call () method is the same as the Apply () method, and they differ only in the way they are received. For the call () method, the first parameter is the this value does not change, changing the rest of the parameters are passed directly to the function. In other words, when using the call () method, the arguments passed to the function must be enumerated individually.
E. Whether to use apply () or call () depends entirely on what kind of method you take to pass parameters to the function. If you intend to pass in the arguments object directly, or if you receive an array in a function, it is certainly more convenient to use apply (), otherwise it might be more appropriate to choose call (). (It doesn't matter which method to use without passing parameters to the function.) )
F. In fact, the transfer of parameters is not the real point of apply () and call (); their really powerful place is the ability to expand the scope in which functions run.
G. The greatest benefit of using call () (or apply ()) to extend the scope is that the object does not need to have any coupling with the method.
function sum (num1,num2) { return num1+num2;}
function CallSum1 (num1,num2) { // incoming arguments object return sum.apply ( this , arguments); }
function callSum2 (num1,num2) { // incoming array return sum.apply (this , [num1,num2]);}
function callSum3 (num1,num2) { // incoming array return sum.apply (window,[num1,num2] );}
function callSum4 (num1,num2) { // incoming parameter list return sum.call (this , num1,num2);}
//callSum1 () passes this as this value when executing the sum () function (because it is called in the global scope, called in the global scope), so the window object is passed in and the arguments object. //?Console.log (CALLSUM1 (10,10));// -Console.log (callSum2 (10,10));// -Console.log (CALLSUM3 (10,10));// -Console.log (CALLSUM4 (10,10));// -Window.color= "Red";varO={color: "Blue"};functionSaycolor () {Console.log ( This. color);} Saycolor (); //RedSaycolor.call ( This);//RedSaycolor.call (window);//RedSaycolor.call (o);//Blue
JavaScript apply () and call ()