A brief introduction to call and apply

Source: Internet
Author: User

Call,apply is basically the same, the difference is the transfer of parameters

<!doctype html>window.onload=function  () {    function  fn1 (A, b)     {        Console.log (this);        Console.log (a+b);    }        Fn1.call (this,1,2);  }</script>

Get the result is, document,3, don't believe you in Chrome, FF open look
Call can do the job, apply is also capable, but the form is a little different

Fn1.apply (this, [+]);

Apply the second parameter is shown in an array form,

Here is a more typical example to illustrate the use of apply

We're looking for the largest number in a bunch of arrays, and that's what we do.

var arr=[3,55,99,3,62,83,17];    Console.log (Math.max (3,55,99,3,62,83,17));

The results are shown to be 99.

But when the array is very long, or is not quite sure what the number is, how do we judge the maximum value in it? This is the apply appearance,

Console.log (Math.max.apply (null, arr));

The previous null can be left out of the way, plug the array in, and get the result 99.

A brief introduction to 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.