In Javascript, the first parameter received by setTimeout and setInterval is a string or a function. When using setTimeout in an object to delay calling the method of the object
function obj() {
this.fn = function() {
alert("ok");
console.log(this);
setTimeout(this.fn, 1000);//Directly use this to refer to the current object
}
}
var o = new obj();
o.fn();
Then we found that the above code is not the desired result. The reason is that this in setTimeout points to window, so the function to be called becomes window.fn and is undefined. , so it was a tragedy. So the key to the problem is to get the reference of the current object, so there are the following three methods
// 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. Unfortunately, the Function.prototype.bind method is a new standard in ES5. After testing the IE series, I found that it is not supported by IE6-8. , only IE9 can be used. If you want to be compatible, you have to simply simulate bind. Look at the code below
// Method 2:
function obj() {
this.fn = function() {
alert("ok");
setTimeout((function(a,b){
return function(){
b.call(a);
}
})(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-executing anonymous function, that is The parameters a and b inside return a closure, and use the call method to make this point to the correct point. The following is a simpler method
// Method three:
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 closure, so as to 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 an alias that and to get the current scope through closure, to Access the saved object that; when there are multiple layers of nested functions or setTimeout, setInterval and other methods in the object method, this is lost (that is, this does not point to the current object but window), so save var that = this in the correct scope where this points. It becomes very practical