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 is a difference, 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 is the call method;
Description: A.call (b,arg1,arg2.) Is the method of the A object applied to the B object
A.apply (b,[arg1,arg2,....]) Also the method of a object is applied to the B object, but the second parameter is different;
For example:
function Add (A, B)
{
alert (A+B);
}
function reduce (A, B)
{
Alert (A-B);
}
Add.call (reduce,1,5)//Apply the Add method to reduce with a result of 6
function Add (A, B)
{
alert (A+B);
}
function reduce (A, B)
{
Alert (A-B);
}
Add.apply (reduce,[1,5])//Apply the Add method to reduce with a result of 6
JS inside the implementation of inheritance and change this reference is also through call and apply
For example
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
Change the reference for this
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
The differences and explanations of call and apply in JavaScript