Call and apply

Source: Internet
Author: User

These two are encountered when talking about this, and they can change the context of the function this, changing its point

The only difference between the two is the difference in the parameters of the communication

Obj.call (Thisobject,arg1,arg2 ...);

Obj.apply (Thisobject,[arg1,arg2 .....));

If the parameters have been determined, you can use call directly, if the parameters are dynamic, then use apply more appropriate

Example

1 functioncat () {};2Cat.prototype={3Food: "Fish",4Sayfunction(){5Alert ("I Love" + This. food);6    }7 }8 varNewcat =NewCat ();9Newcat.say ();//I Love fishTen  One varDog = {food: "Bone"}; ANewCat.say.call (dog);//I Love Bone

This way the newcat is pointing to the dog.

If you think about it in a different way, it doesn't count as inheritance.

1 varParent=function(){2     This. Name= "JSC";3     This. Age = 25;4 }5 varChild={};6Console.log (child);//{} object7 8 Parent.call (child);9Console.log (child);//{name: "JSC", age:25}

Can be used when judging variable types

When we use typeof to determine the type of variable, if it is array,date and so on, all return to object, so we can not determine which is the specific kind of

You can use the call

For example

1 var array = []; 2 3 console.log (typeof array);   //   Object45//[Object,array]

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.