The call () and apply () in JS

Source: Internet
Author: User

1. Common examples

function Add (A, b) {

alert (A+B);

}

function Sub (A, b) {

Alert (A-B);

}

Add.call (sub,4,3); equivalent to add (4,2);

2. Change the role

function Animal () {

This.name= "Animal";

This.showname=function () {

alert (this.name);

}

}

function Cat () {

This.name= "Cat";

}

var animal=new animal ();

var cat=new cat ();

By using the call or Apply method, the ShowName () method that originally belonged to the animal object is given to the object cat, even though the cat has the same name ShowName method does not execute.

Animal.showName.call (Cat, ",") = =   animal.showName.apply (cat,[]); The output is Cat

3. Implementing inheritance

function Animal (name) {

This.name=name;

This.showname= function () {

alert (this.name);

}

}

function Cat (name) {

Animal.call (this) means that the Animal object is used instead of the this object, so there is no Animal of all the properties and methods in Cat, and the Cat object can directly invoke the Animal method and properties.

Animal.call (this, name);

}

var cat = new Cat ("Black cat");

Cat.showname ();

4. Multiple inheritance

function Class10 () {

this.showsub= function (A, b) {

Alert (A-B);

}

}

function Class11 () {

This.showadd = function (A, b) {

Alert (A-B);

}

}

function Class2 () {

Class10.call (this);

Class11.call (this);

}

Call () and apply () in

JS

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.