The difference between apply, call, and bind in javascript is applybind.
In JS, these three are all used to change the point of this object of the function. What are their differences.
Before talking about the difference, let's summarize the similarities of the three:
1. They are all used to change the point of this object of the function.
2. The first parameter is the object to which this points.
3. You can use subsequent parameters to pass parameters.
So where are their differences? Let's look at an example first.
Var xw = {name: "", gender: "male", age: 24, say: function () {alert (this. name + "," + this. gender + ", this year" + this. age) ;}} var xh = {name: "Xiaohong", gender: "female", age: 18} xw. say ();
There is nothing to say. It must be Mr. Wang, male, 24 this year.
So how can we use the xw's say method to display xh data.
The call can be as follows:
1. xw. say. call (xh );
Apply can be like this:
1. xw. say. apply (xh );
For bind, the following is required:
1. xw. say. bind (xh )();
If you write xw. say. bind (xh) directly, there will be no results. Do you see the difference? Both call and apply are direct calls to functions, while the bind method returns a function. Therefore, you need to () to call the function later.
So what is the difference between call and apply? Let's rewrite the example a little.
Var xw = {name: "", gender: "male", age: 24, say: function (school, grade) {alert (this. name + "," + this. gender + ", this year" + this. age + ", on" + school + "+ grade) ;}} var xh = {name:" Xiaohong ", gender:" female ", age: 18}
We can see that there are two more parameters for the say method. We use the call/apply parameter to pass the parameter.
This is the case for call.
1. xw. say. call (xh, "Experimental Primary School", "sixth grade ");
This is the case for apply.
1. xw. say. apply (xh, ["Experimental Primary School", "sixth grade"]);
Do you see the difference? The parameters after the call correspond one to one with the say method, while the second parameter of apply is an array. The elements in the array correspond to the say method, this is the biggest difference between the two.
So how does the bind pass the parameter? It can pass parameters like a call.
1. xw. say. bind (xh, "Experimental Primary School", "sixth grade ")();
However, because the bind returns a function, we can still pass the parameter when calling it.
1. xw. say. bind (xh) ("Experimental Primary School", "sixth grade ");
The difference between apply, call, and bind in the above javascript is all the content shared by the editor. I hope to give you a reference and support for the customer's house.