In JS, these three points are used to change the function of this object, what kind of difference they have it.
Before the difference is still said to sum up the three similarities:
1, are used to change the point of this object's function.
2, the first argument is to point to this object.
3, subsequent parameters can use parameter passing.
So where is the difference between them, and look at an example.
- var xw = {
- name: "Amy"
- gender : "男",
- age : 24,
- say : function() {
- alert(this.name + " , " + this.gender + " ,今年" + this.age);
- }
- }
- where xh = {
- name: "Little Red"
- gender : "女",
- age : 18
- }
- xw.say();
Itself is nothing to say, the display is certainly Wang, male, 24 this year.
So How to say method to display data xw xh it.
For the call can be:
- xw.say.call(xh);
You can apply for this:
- xw.say.apply(xh);
And it needs to bind this:
- xw.say.bind(xh)();
If you write xw.say.bind (xh) will not have any immediate results, see the difference yet? call and apply all direct calls to the function, while still bind method returns a function, and therefore need to back () to be called can.
So call and apply what difference does it? We have examples of some redrafting.
- var xw = {
- name: "Amy"
- gender : "男",
- age : 24,
- say : function(school,grade) {
- alert(this.name + " , " + this.gender + " ,今年" + this.age + " ,在" + school + "上" + grade);
- }
- }
- where xh = {
- name: "Little Red"
- gender : "女",
- age : 18
- }
The method can be seen say more than two parameters, we pass by reference parameters call / apply the.
For this call is
- xw.say.call (xh, "Experimental Primary School", "sixth grade");
For apply is this
- xw.say.apply (xh, [ "Experimental Primary School", "sixth grade Zhengzhou psoriasis hospital "]);
See the difference yet, call back and say parametric method is one to one, and apply the second argument is an array, the array elements are and say one to one method, which is both the largest difference.
So how bind parameter passing it? It can be passed as parameters like call.
- xw.say.bind (xh, "Experimental Primary School", "sixth grade") ();
However, due to still bind a function to return, so we can then pass parameters when invoked.
- xw.say.bind (xh) ( "Experimental Primary School", "sixth grade");
This switched: https://www.cnblogs.com/cosiray/p/4512969.html