In JavaScript, settimeout and setinterval receive the first argument is a string or a function, when the object's method is called with settimeout delay in an object
Copy Code code as follows:
function obj () {
This.fn = function () {
Alert ("OK");
Console.log (this);
SetTimeout (This.fn, 1000);//Use this to refer to the current object directly
}
}
var o = new obj ();
O.fn ();
Then we found that the above code is not the desired result, because the settimeout inside of this is pointing to window, so the function to call becomes window.fn as undefined, so tragedy. So the key to the problem is to get a reference to the current object, so here are three ways
Copy Code code as follows:
Method One:
function obj () {
This.fn = function () {
Alert ("OK");
Console.log (this);
SetTimeout (This.fn.bind (this), 1000);//Bind the current object by Function.prototype.bind
}
}
var o = new obj ();
O.fn ();
This can get the correct results, unfortunately Function.prototype.bind method is ES5 new standards, testing the IE series found ie6-8 are not supported, only ie9+ can be used. To be compatible you have to simply simulate bind, look at the following code
Copy Code code as follows:
Method Two:
function obj () {
This.fn = function () {
Alert ("OK");
SetTimeout ((function (a,b) {
return function () {
B.call (a);
}
}) (This,this.fn), 1000)//Analog Function.prototype.bind
}
}
var o = new obj ();
O.fn ();
First, the current object and object method is passed through a self executing anonymous function, which is the parameters A and b inside, and then returns a closure, which is made to the correct point by the call method. Here are the simpler ways
Copy Code code as follows:
Method Three:
function obj () {
This.fn = function () {
var that = this;//Save current Object this
Alert ("OK");
settimeout (function () {
That.fn ();
}, 1000;//To get the current scope through the closure, good access to 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 is alias that and get the current scope through the closure to access the saved object that; When the object method contains multiple nested functions or settimeout, SetInterval and so on methods lose this (i.e. this does not point to the current object but window), so it is practical to point to the correct scope to save var that = this