var a = { User: "Bgg", fn:function () { console.log (this.user); }} var B = a.fn;b (); Undefined
We want to print the user in object A but print out what's going on with the undefined? If we directly execute A.fn () is possible.
But sometimes we have to save this object to another variable, so we can do it in the following way.
1. Call ()
var a = { User: "Bgg", fn:function () { console.log (this.user);//bgg }}var B = A.fn;b.call (a);
The meaning of B.call (a) here is to point B to a, so this points to a.
The call method can add multiple parameters in addition to the first argument, as follows:
var a = { User: "Bgg", fn:function (e,ee) { console.log (this.user);//bgg Console.log (e+ee);//3 } }var B = A.fn;b.call (a,1,2);
Here call in three parameters understand: the first parameter A, is to change the direction of B, 1 and 2 is to take the FN function as a parameter.
2. Apply ()
The Apply method is somewhat similar to the call method, and it can also change the point of this
var a = { User: "Bgg", fn:function () { console.log (this.user);//bgg }}var B = a.fn;b.apply (a);
The same applies can have multiple parameters, but the difference is that the second parameter must be an array, as follows:
var a = { User: "Bgg", fn:function (e,ee) { console.log (this.user);//bgg Console.log (e+ee);//11 }} var B = a.fn;b.apply (a,[10,1]);
Note If the first argument to call and apply is NULL, then this refers to the Window object
var user= "XM"; var a = { User: "Bgg", fn:function () { console.log (this.user);//xm } } var b = A.fn; B.call (NULL);
3. Bind ()
The Bind method is somewhat different from the call and apply methods, but they can be used to change the point of this anyway.
Let's talk about their differences first.
var a = { User: "Bgg", fn:function () { console.log (this.user); }} var B = A.fn;b.bind (a);
We found that the code was not printed, yes, that's the difference between bind and call, the Apply method, and the Bind method actually returns a modified function.
var a = { User: "Bgg", fn:function () { console.log (this.user); } } var b = A.fn; Console.log (B.bind (a))
return value:
Now let's try to run this function:
var a = { User: "Bgg", fn:function () { console.log (this.user); BGG } } var b = A.fn; B.bind (a) ();
The same bind can have multiple parameters and can be added again when the parameters are executed, but it is important to note that the parameters are in the order of the formal parameter.
var a = { User: "Bgg", fn:function (q,w,e) { console.log (this.user); BGG Console.log (q,w,e); 1 2 3 } } var b = A.fn; B.bind (a,1,2,3) ();
Summary: Call and apply are changes in the context of this and immediately execute this function, the bind method can let the corresponding function when it is called when the calling, and the parameters can be added at the time of execution, this is their difference, according to their actual situation to choose to use.
Change the Call,apply,bind method of this point