How to use the functions of apply and call

Source: Internet
Author: User

Although apply and call can implement same function. However, there is a litter different between them. Please pay attention-to-look at the examples below:

Define an object person

1 person=function(name,age) {2this    . name=name; 3    this. age= age; 7 }89var pin=New//Create an object

After then, we need to define some functions (skating,running,eating) with different parameter s respectively.

1 functionSkating ()//It don ' t need any parameter2 {3Alert This. name+ "Like skating!");4 }5 6 functionRunning (distance)//It need 1 parameter7 {8Alert This. name+ "can only run" +distance+ "meters!");9 }Ten  One functionEating (FRUIT1,FRUIT2)//It need 2 paramters A { -Alert This. name+ "Like eating" +fruit1+ "and" +fruit2+ "!"); -}

Now, I'll use the Apply and call respectively.

// After using apply skating.apply (PIN); Running.apply (pin,[); Eating.apply (pin,["Apple", "Orange"]); Results respectively:pin like skating!  meters! Pin like eating apply and orange!

// After using the call Skating.call (PIN); Running.call (PIN,+), Eating.call (PIN,"apple", "orange"); Results respectively:pin like skating!  meters! Pin like eating apply and orange!

From the results above, we can know the differences between apply and call:

Same:

1. apply and call All Can make object pin implement Sakting , running and , respectively. Exactly, object pin own three new functions (sakting ,  RUNNING  and eating ).

2. The first parameter pin is the replace the key , this among three functions. So, when the three functions call the variable this.name, the key "This was not three functions T Hemselves but an object pin.

3. If the first paramter is null, the Global Object window would replace it.

4. If the function (such as skating) don ' t need any paramters, the apply and call is same.

Difference:

If the function need a parameter at least, the parameter should is a array using apply. For the call, without any constraints.

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.