The function of call and apply in JS is to change function calling object, implement inheritance
For example:
Changing the Calling Object
function A (x, y) { alert (x+y);} function b (x, y) { alert (x-y);} A.call (b,1,5)//The A method is given to B with a result of 5
Change this point
Function B () { alert (this)}b ();//windowb.call ();//windowb.call ("a", 2,3);//a
Method B is defined as a Global object window when B.call ("a"), method B has = is called by the object "a"
var a = function () { alert (this.name); }; var b = { name: "Xiaohua" }; A.call (b) //object B with Nmae property call method The this in the A,a method is pointed to B
Implementing inheritance
function Animal (name) { this.name=name; This.showname=function () { alert (this.name)}}
function Cat (name) { animal.call (this,name);//applies Animal to Cat, so cat has all the properties and methods of Animal}
var cat = new Cat ("Black cat"); Cat.showname (); Browser Popup Black Cat
Apply and call are used the same way, only with different methods of communication
A.call (B,arg1,arg2 ...)//method. Call (object, parameter, parameter ....) )
A.apply (B,[ARG1,ARG2])//method. Apply (object, [parameter, parameter .... ])
Some other clever uses of apply
(1) Math.max can be implemented to get the largest of the array:
because Math.max does not support Math.max ([PARAM1,PARAM2]), which is an array, it supports Math.max (param1,param2 ...), so you can solve Var max= according to the characteristics of apply. Math.max.apply (Null,array), so it's easy to get the largest item in an array (apply will convert an array to a parameter by passing it to the method)this block in the call when the first parameter gave 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 directly passed a null past. This method can also be implemented to get the smallest item in the array: Math.min.apply (Null,array) (2) Array.prototype.push can implement merging of two arraysThe same push method does not provide an array of push, but it provides push (Param1,param2...paramn) and can also use apply to convert the array, namely:1.var arr1=new Array ("1", "2", "3");2.var arr2=new Array ("4", "5", "6");3.array.prototype.push.apply (ARR1,ARR2); //Gets the length of the merged array, because push is to return the length of an array as well as to understand, arr1 called the Push method, and the parameter is a collection of arguments that convert the array to a parameter list by using apply
The differences and explanations of call and apply in JavaScript