Call (), apply (), bind ()

Source: Internet
Author: User

1. The call () and apply () methods are present in each function object, and in the prototype

2. Grammar is
Function.apply (Thisobj,[a,b,c])

Function.call (THISOBJ,A,B,C)

3. Common Ground

is used to call a method in place of another object, changing the object context of a function to a new object specified by Thisobj

4, different points

Apply () takes two parameters and puts the parameters in the array

Call () accepts multiple parameters, and the argument is a list of strings

5. Example

function Add (A, b) {

return a+b;
}
function Sub (A, b) {
return a-B;
}

var a1 = add.apply (sub,[4,2])

var a2 = sub.apply (add,[4,2])

var a3 = Add.call (sub,4,2)

Console.log (A1,A2,A3)

6. Implementing inheritance

function Animal (name) {
THIS.name = name;
This.showname = function () {
alert (this.name);
}
}

function Cat (name) {
Animal.apply (This,[name]);
}

var cat = new Cat ("cuckoo");
Cat.showname ();

The use of/*call * *
Animal.call (This,name);

Call (), apply (), bind ()

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.