In JS, call and apply their role is to bind the function to another object to run, the two only in the definition of the parameters of the way there are differences, let me give you a brief introduction of the use of calling and apply.
In the Web front-end development process, we often need to change this point, usually we think of the call method, but for the understanding of call many people are not very clear, then the following small series to give you a detailed talk about call and apply the detailed knowledge
I. Definition of the call method
Everyone in Baidu can search for call, the definition of call is very clumsy. In my understanding, A.call (b,arg1,arg2.) Is the method of the A object applied to the B object. For example, the following example:
| The code is as follows |
Copy Code |
|
function Add (A, B)
{
alert (A+B);
}
function reduce (A, B)
{
Alert (A-B);
}
Add.call (reduce,1,3)//Apply the Add method to reduce with a result of 4 |
second, call can change this point
The following example:
| The code is as follows |
Copy Code |
|
Function B ()
{
Alert (This)
}
b (); Window
B.call (); Window
B.call ("A", 2, 3); A |
Let's look at a complicated example:
| The code is as follows |
Copy Code |
|
function Animal ()
{
This.name= "Animal";
This.showname=function ()
{
Alert (this.name)
}
}
function Cat ()
{
This.name= "Cat";
}
var animal = new animal ();
var cat = new Cat ();
Animal.showname (); The result is animal
Animal.showName.call (CAT); Originally, Cat did not have a ShowName method, but the animal ShowName method was applied to cat using the call method, so the result is cat |
iii. realization of inheritance
Here's an example:
| The code is as follows |
Copy Code |
|
function Animal (name)
{
This.name=name;
This.showname=function ()
{
Alert (this.name)
}
}
function Cat (name)
{
Animal.call (This,name); Animal is applied to cat, so cat has all the properties and methods of animal
}
var cat = new Cat ("Black cat");
Cat.showname (); Browser Popup Black Cat |
Iv. use of Apply
The use of apply and call is not the same in one place, but in addition, the other places are basically identical
A.call (B,arg1,arg2 ...)
Apply (B,[ARG1,ARG2])//apply has only 2 parameters, which will call the parameters (Arg1,arg2 ... ) placed in an array as the second parameter of apply
Call and apply method differences