The difference between js:call () and apply

Source: Internet
Author: User

Each function contains two non-inherited methods: Call () and apply ();

Call () method: parameter, the first one is the calling function in the scope (this), the rest of the parameters are passed directly to the function widening scope, parameters must be listed individually when passing parameters.

Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
alert (This.color);

}
Saycolor (); Red
Saycolor.call (this);//red
Saycolor.call (window); Red
Saycolor.call (o);//blue

function sum (NUM1, num2) {
return NUM1 + num2
}

function Callsum (NUM1, num2) {
return Sum.call(this,num1,num2);
}
Alert (Callsum (10,10)); 20

The Applay () method also accepts two parameters:

One is the scope in which the function is run (this);

The other is a parameter array (which can be an instance of an array, such as [num1,num2]), or a arguments object;

function CallSum1 (num1,num2) {
return sum.apply(this,arguments);
}

function callSum2 (NUM1, num2) {
return sum.apply(this,[num1,num2]);
}
Alert (CALLSUM1 (10,10));
Alert (callSum2 (10,10));

The difference between applay () and call ():

Applay () and call () the same point: The purpose is to invoke the function in the scope of the attribute (set the value of this formation in the function body)
The difference between the two: accept the second parameter, call () accepts the parameters must be enumerated, and Applay (), can be a arguments object is also an array instance.

The difference between js:call () and apply

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.