In JS, these three are used to change the function of the this object to the point, they have what kind of difference. Before we say the difference, we should summarize the similarities of the three: 1, are used to change the function of the this object point. 2. The first parameter is the object to which this is directed. 3. You can use the following parameters to pass the parameter. So where are their differences, first look at an example.
- var XW = {
- Name: "Xiao Wang",
- Gender: "Male",
- Age:24,
- Say:function () {
- Alert (THIS.name + "," + This.gender + ", this year" + this.age);
- }
- }
- var xh = {
- Name: "Little Red",
- Gender: "Female",
- Age:18
- }
- Xw.say ();
Copy Code
itself nothing to say, the show is certainly Xiao Wang, male, 24 this year. So how to use the XW say method to display the XH data. For call you can do this:
- Xw.say.call (XH);
Copy Code
For apply you can do this:
- Xw.say.apply (XH);
Copy Code
And for bind, you need this:
- Xw.say.bind (XH) ();
Copy Code
If the direct write Xw.say.bind (XH) will not have any results, see the difference? Both call and apply are direct calls to the function, and the Bind method returns a function, so it needs () to be called later. So what's the difference between call and apply? Let's rewrite the example a little bit.
- var XW = {
- Name: "Xiao Wang",
- Gender: "Male",
- Age:24,
- Say:function (School,grade) {
- Alert (THIS.name + "," + This.gender + ", this year" + This.age + "," + School + "on" + Grade ");
- }
- }
- var xh = {
- Name: "Little Red",
- Gender: "Female",
- Age:18
- }
Copy Code
We can see that the say method has more than two parameters, and we use the parameters of call/apply to pass the parameter. For call, that's it.
- Xw.say.call (XH, "Experimental Primary School", "Six Grade");
Copy Code
And for apply, that's it.
- Xw.say.apply (xh,["Experimental Primary School", "Red Hot Platform Catering Service Co., Ltd."]);
Copy Code
See the difference, the argument behind call is one by one corresponding to the Say method, and the second argument to apply is an array, and the elements in the array correspond to one by one of the Say method, which is the biggest difference between the two. So how does bind pass? It can pass the argument like call.
- Xw.say.bind (XH, "Experimental Primary School", "Six Grade") ();
Copy Code
However, since BIND is still returning a function, we can also pass the arguments at the time of the call.
- Xw.say.bind (XH) ("Experimental Primary School", "Six Grade");
The difference between apply, call, and bind in JavaScript