Call and apply in JavaScript

Source: Internet
Author: User

I. Definition of the Call method

Everyone in Baidu can search call, the definition of call is very clumsy. In my understanding, A.call (B,arg1,arg2 ...) Is the method of a object applied to the B object. For example, the following example:

The code is as follows

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

Two. Call can change this point

The following example:

The code is as follows

Function B ()
{
Alert (This)
}
b (); Window
B.call (); Window
B.call ("A", 2, 3); A

Let's look at a complex example:

The code is as follows

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); The original cat had no ShowName method, but the animal ShowName method was applied to cat by the call method, so the result was cat

Third, the implementation of inheritance

The following example:

The code is as follows

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 pops Black Cat

Four. Apply Usage

There is only one place where apply and call are different, except that the other places are basically the same.

A.call (B,arg1,arg2 ...)

Apply (B,[ARG1,ARG2])//apply has only 2 parameters, it will call the argument (Arg1,arg2 ...) Put in an array as the second parameter of apply

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.