Call () function, apply () function difference and meaning

Source: Internet
Author: User

The meaning of using the Apply function or the call function:

In the face of object programming, when a object calls other objects instead of the A object method, all of the this references in the method point to the object in which the method resides, not the context of the current code, which is a object.

To maintain the original point of this (that is, the A object), you need to use the Apply or call function.

The difference between apply () and call ():

Apply and call, their role is to bind the function to another object to run

The prototypes were

Function.prototype.apply (Thisarg,argarray);
Function.prototype.call (Thisarg,[arg1],[arg2 ...]);

As you can see, the first parameter is named Thisarg, which means that the this pointer inside all functions is assigned a value of Thisarg, allowing another object instance to pass into the function.

If the Thisobj parameter is not provided, then the Global object is used as the thisobj.

The difference is that the second argument, the Apply () function passes in the numeric value as an array, and the call () function passes directly to multiple values in a free form.

Example:

function accomodation () {

This.isalarmed=false;

}

var alarmsystem={

Arm:function (message) {

This.isalarmed=true;

alert (message);

},
Disarm:function (message) {
This.isalarmed=false;
alert (message);
}

};

var myhouse = new accomodation ();

AlarmSystem.arm.call (Myhouse, "Alarm activated");

alert (myhouse.isalarmed); True the this value in the arm () function points to the Myhouse object through call (), which changes the properties of the Myhouse object

AlarmSystem.disarm.apply (myhouse,["Alarm activated"]);

alert (myhouse.isalarmed); The this value in the flase arm () function points to the Myhouse object through call (), which changes the properties of the Myhouse object

Call () function, apply () function difference and meaning

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.