Detailed explanation of the difference between call apply and bind in javascript

  • 2021-10-13 06:21:44
  • OfStack

In JS, all three are used to change the direction of the this object of the function. What is the difference between them?

Before talking about the differences, we should sum up the similarities between 1 and 3:
1. Are used to change the pointing of the this object of the function.
2. The first parameter is the object that this points to.
3. Subsequent parameters can be used to transmit parameters.

So what is the difference between them? Let's look at an example first.


var xw = {
     name : " Xiao Wang ",
     gender : " Male ",
     age : 24,
     say : function() {
       alert(this.name + " , " + this.gender + " , This year " + this.age);                
        }
     }
     var xh = {
       name : " Xiao Hong ",
       gender : " Female ",
       age : 18
       }
     xw.say();

It must be Xiao Wang, male, 24 this year.
So how to use the say method of xw to display the data of xh.
For call, you can do this:


xw.say.call(xh);

For apply, you can do this:


xw.say.apply(xh);

For bind, it needs to be like this:


xw.say.bind(xh)();

If you just write xw. say. bind (xh), you won't get any results. See the difference? call and apply are both direct calls to functions, while the bind method still returns a function, so it needs () to call later.
So what's the difference between call and apply? Let's rewrite the example a little.


        var xw = {
            name : " Xiao Wang ",
            gender : " Male ",
            age : 24,
            say : function(school,grade) {
                alert(this.name + " , " + this.gender + " , This year " + this.age + " , In " + school + " Upper " + grade);                
            }
        }
        var xh = {
            name : " Xiao Hong ",
            gender : " Female ",
            age : 18
        }

It can be seen that the say method has two more parameters, and we pass the parameters through the parameters of call/apply.
This is the case for call


xw.say.call(xh," Experimental primary school ","6 Grade ");    

For apply, this is the case


xw.say.apply(xh,[" Experimental primary school ","6 Grade "]);

See the difference, the parameters after call correspond to 11 in say method, while the second parameter of apply is an array, and the elements in the array correspond to 11 in say method, which is the biggest difference between the two.
So how does bind pass on the reference? It can pass parameters like call.


xw.say.bind(xh," Experimental primary school ","6 Grade ")();

However, since bind still returns a function, we can pass parameters at the time of call.


xw.say.bind(xh)(" Experimental primary school ","6 Grade ");

The above is the detailed explanation of the differences between call, apply and bind in javascript. For more information about JavaScript, call, apply and bind, please pay attention to other related articles on this site!


Related articles: