How to understand and skillfully use the JS in the call and apply?

Source: Internet
Author: User

In the front-end development process, we often need to change the this point, usually we think of the call method, but for the understanding of call many people are not very clear, then the following small mention Mo will give you a detailed talk about calls and apply the detailed knowledge.

The first parameter of call is passed to the object, and the parameter can be any type (including null). Example: Call (OBJ,ARG1,ARG2,ARG3) apply the first parameter to the object, the argument can be an array or argumentsObject. Example: Apply (OBJ,[ARG1,ARG2,ARG3]) call and apply are in order to change this dynamically, when an object does not have a method, but others, we can use call or apply the method of other objects to operate. For example, we often define this:
 1  function   Teemo () { 2   This . gift= "mushroom" ;  3  this . say= function   () { 4  console.log ("I Love" +this  .gift);  5  }  6  }  7   var  smallteemo = new   Teemo;  8  Smallteemo.say (); 

But if we have an object heimerdinger= {gift: "Battery"}, we don't want to redefine it say method, Then we can use call or Apply with Smallteemo say method: SmallTeemo.say.call (Heimerdinger);

For the convenience of memory:

Titus Mushroom, Big Head pendulum fort, Anne summon Bear.

A big head wants to grow mushrooms.

Mention mo. mushrooms. Call (big Head, mushroom)

You can grow mushrooms with a big head.

Don't be naughty, you want to summon a bear.

Annie Summon Bear. Call (Titus, Bear)

Just remember that.

How to understand and skillfully use the JS in the 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.