The call () function and the Apply () function in JS:
1, the main role: is used to specify the scope and the parameters
(1) to specify a scope
1Window.color ="Red";2 varo = {color:"Blue" };3 varSaycolor =function () {4 Debugger;5Alert This. color);6 }7 Saycolor ();8 9Saycolor.apply ( This);//undefindedTen saycolor.apply (window);//red OneSaycolor.apply (o);//blue
(2) for the transfer of parameters
1that = This;2 varsum =function (n1, n2) {3 Debugger;4 This. N1 =N1;5 This. N2 =N2;6 return This. N1 + This. n2;7 }8 varAPPLYSUM1 =function (n1, n2) {9THAT.AAAAA =function () {};Ten returnSum.apply (that, arguments);///that's all Windown . One } A varApplySum2 =function (n1, n2) { -THAT.BBBBB =function () {}; - returnSum.apply (that, [N1, N2]);///that's all Windown . the } - varCallsum =function (n1, n2) { -THAT.CCCCC =function () {}; - returnSum.call (that, N1, N2);///that's all Windown . + } -Alert (APPLYSUM1 (Ten, A));// A +Alert (APPLYSUM2 (Ten, -));// at AAlert (Callsum ( -,Ten));// -
2, apply () and call () analysis
Apply: Methods can hijack another object's method, inheriting another object's properties.
Function.apply (obj,args) method can receive two parameters
OBJ: This object will replace the This object in the function class
Args: This is an array, which is passed as a parameter to function (args-->arguments)
Call: Same as apply, except that the argument list is not the same.
Function.call (obj,n1,n1,...);
3, apply () skillfully use
(1) Math.max can be implemented to get the largest item in the array
Because the Math.max parameter does not support Math.max ([PARAM1,PARAM2]), which is the array
But it supports Math.max (param1,param2,param3 ...), so you can solve the Var max=math.max.apply (Null,array) According to the characteristics of the just apply. This makes it easy to get the largest item in an array (apply will change a number assembly to a parameter by passing it to a method)
This block in the call when the first parameter gave a null, this is because there is no object to call this method, I just need to use this method to help me to calculate the return of the results on the line. So I passed a null past directly.
1 vararg = [5,2,1,6,8];2 varmax = Math.max.apply (NULL, ARG);3 varmin = Math.min.apply (NULL, ARG);4Alert"Max:"+ Max +"---min:"+ min);
Results: Max:8---min:1
(2) Math.min can be implemented to get the smallest item in the array
Likewise and Max is a thought var min=math.min.apply (Null,array);
(3) Two numbers can be combined and
1 var ar1 = [125]; 2 var ar2 = [579]; 3 Ar1.push.apply (AR1, AR2);//ar1=[1,2,5,5,7,9]
and Ar1.push (AR2);//Results ar1=[1,2,5,[5,7,9]]
The call () and apply () in JS