The difference between call, apply and bind in JS

Source: Internet
Author: User

Objective

About JS in the call, apply and bind the difference between the three, this should be a commonplace problem, is also a front-end interview often encounter a topic, so also take time to get it over.

Role

Call, apply, and bind are all methods in JavaScript, and their common role is to change the context in which the function executes, that is, to change the direction of this when the function executes. Let's take a look at the following example:

1 functionAnimal (name) {2      This. Name =name;3 }4Animal.prototype.getName =function() {5Console.log ( This. Name);6 }7 varDog =NewAnimal (' Dog ');8 varCat = {9Name: ' Cat 'Ten }; OneDog.getname ();//Dog ADog.getName.call (CAT);//Cat -Dog.getName.apply (CAT);//Cat -Dog.getName.bind (CAT) ();//Cat

In the example above, the point of this in the first GetName method is the dog object, so the output is ' dog ' at the beginning of the execution, but when using call, apply, and bind to change the context of getName execution, the pointer of this becomes a cat object. So the name of the output at this point is the name of the Cat object, ' cat '.

Difference

Although the call, apply, and bind three methods are used to change the point of this when the function is executed, there are some differences in use.

(1) The difference between call, apply and bind

Call and apply both change the context of the function and immediately execute the function, and bind is a function that returns the change context.

(2) The difference between call and apply

The first parameter of call and apply is the context object to be changed, and call starts with the second argument and subsequent arguments are presented in the form of a parameter list, and apply is placed in an array as its second argument in addition to the context object to be changed.

1 fn.call (obj, arg1, arg2, arg3 ...);
2 fn.apply (obj, [Arg1, Arg2, arg3 ...]);

The difference between call, apply and bind in JS

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.