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