The Apply () method and the call () method

Source: Internet
Author: User

Obj.func.call (OBJ1)///is to consider obj1 as obj, call the Func method, and consider the first argument as the object of a function call, which can be seen as a method of using obj for obj1

The ECMAScript specification defines the call () and apply () methods for all functions.

Note: The first argument to call () and apply () is a function object that needs to be called.

In the function body the value of this is a pointer to the caller, the first argument, and the remaining arguments are the values that need to be passed to the function

The difference between call () and apply () is that the remaining argument, call (), the remaining argument can be any value, and the remaining value of apply () can only be an array.

For example: function Add (A, b) {

return a+b;

}

function Sub (A, b) {

return a-B;

}

Usage of apply ():

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

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

Use of call ():

var a1=add.call (add,4,2);

var a2=sub.call (sub,4,2);

JS think he is omnipotent, since the high-level language can inherit, I JS can also inherit

function Fun1 () {

this.a=123;

This.add=function () {

return THIS.A;

}

function fun2 () {

this.a=456;

}

}

var a1=new fun1 ();

var a2=new fun2 ();

var a=a1.add.call (A2); The output is 456.

Here is the method of F1 to F2 to use, F2 can use all the methods in F1, this is not the concept of high-level language inheritance, but also can imitate the high-level language of multiple inheritance

function Fun1 () {

This.add=function () {

return this.a+this.b;

}

This.fun2=function () {

return this.a-this.b;

}

Funtion Fun3 () {

this.a=10;

thi.b=2;

Fun1.call (this);

Fun2.call (this);

}

}

var f3=new fun3 ();

Console.log (F3.add ())//13;

Console.log (F3.sub ())//8

The Apply () method and the call () method

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.