In JS, these three are used to change the function of this object to point to, they have what kind of difference.
Before you say the difference, let's summarize the similarities between the three:
1, are used to change the function of this object to point to.
2, the first argument is the object to point to.
3, all can use the subsequent 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.gend Er + ", this year" + this.age)
;
}
var xh = {
name: "Little Red",
Gender: "Female",
age:18
}
Xw.say ();
There is nothing to say in itself, the show is definitely 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:
1.xw.say.call (XH);
For apply, you can do this:
1.xw.say.apply (XH);
And for bind, you need this:
1.xw.say.bind (XH) ();
If you write Xw.say.bind directly (XH) there will be no results, see the difference? Call and apply are both direct calls to a function, and the Bind method returns a function, so you need to () to invoke it 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 + ", on" + School + + "+ grade);
}
var xh = {
name: "Little Red",
Gender: "Female",
age:18
}
You can see that the say method has two more parameters, we pass the parameters of the call/apply.
For call, that's it.
1.xw.say.call (XH, "Experimental Primary School", "Six Grade");
And for apply, that's it.
1.xw.say.apply (xh,["Experimental Primary School", "six Grade"]);
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.
So how does bind get involved? It can be passed as call.
1.xw.say.bind (XH, "Experimental Primary School", "Six Grade") ();
But since BIND is still returning a function, we can also invoke the argument at the time of the call.
1.xw.say.bind (XH) ("Experimental Primary School", "Six Grade");
Above this JavaScript application, call and bind the use of the difference is small series to share all the content, I hope to give you a reference, but also hope that we support the cloud habitat community.