In Javascript, the first parameter received by setTimeout and setInterval is a string or a function. When setTimeout is used to call the method of this object in an object
Copy codeThe Code is as follows:
Function obj (){
This. fn = function (){
Alert ("OK ");
Console. log (this );
SetTimeout (this. fn, 1000); // use this to reference the current object directly.
}
}
Var o = new obj ();
O. fn ();
Then we found that the above Code is not the desired result because this in setTimeout points to the window, so the function to be called is changed to window. fn to undefined, which is a tragedy. So the key to the problem is to get the reference of the current object. There are three methods as follows:
Copy codeThe Code is as follows:
// Method 1:
Function obj (){
This. fn = function (){
Alert ("OK ");
Console. log (this );
SetTimeout (this. fn. bind (this), 1000); // bind the current object through Function. prototype. bind
}
}
Var o = new obj ();
O. fn ();
This can get the correct results, but unfortunately the Function. prototype. bind method is ES5 new standard, test the IE series found that the IE6-8 is not supported, only IE9 + can be used. To be compatible, You have to simulate bind in a simple way. refer to the following code:
Copy codeThe Code is as follows:
// Method 2:
Function obj (){
This. fn = function (){
Alert ("OK ");
SetTimeout (function (a, B ){
Return function (){
B. call ();
}
}) (This, this. fn), 1000); // simulate Function. prototype. bind
}
}
Var o = new obj ();
O. fn ();
First, pass the current object and object method through a self-executed anonymous function, that is, the parameters a and B in it, then return a closure, and use the call method to make this point correct. The following is a simple method.
Copy codeThe Code is as follows:
// Method 3:
Function obj (){
This. fn = function (){
Var that = this; // Save the current object this
Alert ("OK ");
SetTimeout (function (){
That. fn ();
}, 1000); // get the current scope through the closure, so you can access the saved object that
}
}
Var o = new obj ();
O. fn ();
The two key points of the third method above are to save the current object this as alias that and get the current scope through the closure to access the saved object that. When the object method contains multiple layers of nested functions or setTimeout, setInterval and other methods lose this (that is, this does not point to the current object but window), so it is very practical to save var that = this when this points to the correct scope.