The differences and explanations of call and apply in JavaScript

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.