在 JavaScript 中,setTimeout 與 setInterval 常用於延遲或重複執行函式。若在物件方法中使用計時器,this 指向往往不如預期。
當計時器回呼函式被執行時,this 通常會指向全域物件,而不是原本的方法所屬物件。
var obj = {
value: 'hello',
run: function() {
setTimeout(function() {
console.log(this.value);
}, 1000);
}
};
obj.run();上述程式碼可能印出 undefined,因為 this 已不是 obj。
ES5 提供 bind,可固定 this。
setTimeout(this.run.bind(this), 1000);若環境不支援 bind,可自行模擬。
function bind(fn, context) {
return function() {
return fn.apply(context, arguments);
};
}
setTimeout(bind(this.run, this), 1000);另一種常見做法,是先用區域變數保存 this,再在回呼中使用。
var obj = {
value: 'hello',
run: function() {
var that = this;
setTimeout(function() {
console.log(that.value);
}, 1000);
}
};
obj.run();這種寫法直觀,也相容舊版瀏覽器。
也可透過立即執行函式傳入 this,再回傳內部函式。
setTimeout((function(context) {
return function() {
context.run();
};
})(this), 1000);這三種方式都能修正計時器中的 this。實際選擇時,可依專案環境與可讀性需求決定。若使用現代框架或支援 ES5 的環境,bind 通常最簡潔。