JS Call and apply

Source: Internet
Author: User

function Add (A, b)  {      alert (a+b);  }   function Sub (A, b)  {      alert (a-b);  }    Add.call (Sub,3,1);   
Example 1

The meaning of Example 1 is to replace sub,add.call (sub,3,1) = = Add (3,1) with add, so the result is: alert (4); Note: The function in JS is actually an object, and the function name is a reference to a function object.

var ary=[3,1];   function Add (A, b)  {      alert (a+b);  }   function Sub (A, b)  {      alert (a-b);  }  Add.apply (sub,ary);
Example 2

The meaning in Example 2 is also to replace sub,add.apply (sub,ary) = = Add (3,1) with add, so the result is also: alert (4);

The common point of call and Applay:

1) are used to change the This keyword, such as add.call (sub,3,1) means to replace a sub with add

2) The first parameter in parentheses is the this value to be changed

Call and Apply differences:

The parameters in call are passed in by one, and the arguments in apply are in the form of an array.

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.