The difference between apply and call

Source: Internet
Author: User

Same point:

Can change the execution context of the method (execution environment), the method of one object is handed to another object to execute, and is executed immediately

different points:

callThe method can receive any parameter starting from the second parameter , and each parameter is mapped to the Func parameter of the corresponding location, which can be called by the parameter name, but if all arguments are passed as an array, They are mapped as a whole to the first parameter of the Func, after which the parameters are empty

Liezi:

function Func (A, B, c) {};func.call (obj, 1, 2, 3);//function received parameters are actually 1, 2, 3func.call (obj, [1, 2, 3]);//function receives the parameter Number is actually [1,2,3],undefined,undefined

applyMethod has a maximum of two parameters , the second parameter receives an array or an array of classes, but is converted into a class array into the Func, and is mapped to the parameters of the func corresponding

Liezi:

Func.apply (obj, [1, 2, 3]);//functions receive the function is actually 1, 2, 3func.apply (obj, {    0:1,    1:2,    2:3,    length:3}) ;//function received the parameter is actually 1, 2, 3

Sometimes it's just like me. Apply and call in use at a loss, do not know which to use? Two ways to choose, right?

Very simple, according to the parameters you want to pass the choice, do not need to pass the parameter or only 1 parameters when, call when you want to pass in multiple objects, withapply

Alternatively, if you need to pass in a parameter that is already an array or an array of classes, use apply , if you need to pass in individually, you can consider using it call (if you're not too troublesome)

The difference between apply and call

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.