我无法使用 bind()
在我的内部函数之一中获取正确的上下文。这是我的代码:
return {
/**
* Checks if the table loader is active
* @return {home} Returns this module for chaining
*/
loadStatusLog: function() {
if ($("#status-log-box").length) {
$.getJSON("/Home/CurrentEvents", function(json, status, xhr) {
if (status === "error") {
var errmsg = "Sorry but there was an error: ";
$("#result-msg").html(errmsg + xhr.status + " " + xhr.statusText);
}
else if (status === "success") {
if (json.globalGenerationStatus) {
console.log(this);
this.updateProgressInterval = setInterval(this.updateGenerationProgress, 1000);
}
var html = statusLog(json);
$("#status-log-table").html(html);
}
}.bind(this));
}
return this;
},
/**
* Looks at the generation progress file and updates the progress bar for a running event
* @returns {home} Returns this module for chaining
*/
updateGenerationProgress: function() {
var runningEvent = $(".running-event");
$.ajax({
type: "POST",
url: "/Home/readGenerationStatusFile",
global: false
}).done(function(data) {
runningEvent.css("width", data + "%").attr("aria-valuenow", data);
if (data === "100") {
console.log(this);
clearInterval(this.updateProgressInterval);
$("span", runningEvent).text("Complete").parent().removeClass("running-event").parent().removeClass("active progress-striped");
}
}.bind(this));
return this;
}
};
我的主要目标是从 updateGenerationProgress()
函数中清除 loadStatusLog()
函数内部设置的间隔。 loadStatusLog()
内部的 console.log()
语句输出正确的上下文(此对象),但内部的 console.log()
语句updateGenerationProgress()
的输出 Window 作为上下文。为什么是这样?我对 promise 和背景有什么遗漏吗?
最佳答案
您还需要设置间隔的上下文
this.updateProgressInterval =
setInterval(this.updateGenerationProgress.bind(this), 1000);
否则,在非严格模式下,上下文将设置为 window
(或工作线程),在严格模式下,将设置为 undefined
。
关于javascript - 无法使用 Promise 通过 bind() 获取正确的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24246219/