Similarities and differences between apply () and call () in JavaScript

Source: Internet
Author: User

Each function contains two non-inherited methods, apply (), and call (). The purpose of both methods is to invoke the function in a specific scope, which is actually equivalent to setting the value of the This object in the function body.

The Apply () method receives two parameters: one is the scope in which it is run, and the other is a parameter array. Where the second argument can be an instance of an array, or it can be an arguments object. For example:

function sum (num1,num2) {
return num1+num2;
}
function CallSum1 (num1,num2) {
Return sum.apply (this,arguments);//Incoming arguments object
}
function callSum2 (num1,num2) {
Return sum.apply (this,[num1,num2]);//Incoming array
}
Alert (CALLSUM1 (10,10));//20
Alert (callSum2 (10,10));//20


The call () method has the same effect as the Apply () method, and they differ only in the way that the parameters are received. For the call () method, the first parameter is the this value does not change, changing the rest of the parameters are passed directly to the function. In other words, when using the call () method, the arguments passed to the function must be enumerated individually, for example:

function sum (num1,num2) {
return num1+num2;
}
function Callsum (num1,num2) {
Return Sum.call (this,num1,num2);
}
Alert (Callsum (10,10));//20


In the case of the call () method, Callsum () must explicitly pass in each parameter. The result is nothing different than using apply (). Whether to use apply () or call () depends entirely on what kind of method you are using to pass parameters to the function.


The above summary is from the advanced programming of JavaScript

Similarities and differences between apply () and call () 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.