Call function and apply in JavaScript

Source: Internet
Author: User

The call method in JavaScript enables the current object to invoke the method of another object, that is, to change the point of this

1 varFirst_object = {2Num:423 };4 varSecond_object = {5Num:246 };7 functionMultiply (mult) {8 return  This. Num *mult;9 }TenAlert (Multiply.call (First_object, 5));// About
View Code

The result of the execution is returned at this time, 210. You can see that this in First_object becomes the this in First_object in the current object. And First_object owns all the methods and properties in the current object.

The call function is used in the following ways:

Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])

Thisobj

Selected objects

Arg1,arg2. ArgN

Options are available. The method parameter sequence will be passed.

1 functionClass1 ()2 { 3      This. Name = "Class1"; 4 5      This. Shownam =function() 6     { 7Alert This. Name); 8     } 9 } Ten  One functionClass2 () A {  -      This. Name = "Class2";  - }  the  - varC1 =NewClass1 (); - varC2 =NewClass2 (); -  +C1.showNam.call (C2);

Call means to put the C1 method on the C2, the original C2 is no Shownam () method, now is C1 Shownam () method put to C2 to execute, so this.name should be class2, the result of execution is: alert ("Class2 ");

You can also use call to implement inheritance

function Class1 ()
{
This.showtxt = function (TXT)
{
alert (TXT);
}
}

function Class2 ()
{
Class1.call (this);
}

var C2 = new Class2 ();

C2.showtxt ("CC");

So Class2 inherit Class1, Class1.call (this) means to use the Class1 object instead of the This object, then Class2 all the properties and methods Class1, C2 object can directly call Class1 method to and attributes, the result of execution is: alert ("CC");

The Apply () function is the same as call (), except that the first parameter in the first argument to call () is the same as the one in Call (), and the second parameter is the array of two parameters.

Call function 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.