如何处理 setInterval javascript 的作用域


define(['services/tempService'], function (TempService) {
"use strict";
window.TempClass = {
setIntervalConst : 0,
startTimer: function(){
    var that = this;
    this.setIntervalConst = setInterval(function () {
        that.checkTime();
    }, 1000);
},
checkTime: function() {
    new TempService().getData();
}
};
  return window.TempClass;
});

临时服务.js

define([], function() {
"use strict";
var TempService = function(){
 return{
   getData: function(){
     Service.getData(URL);
  }
};       
};
 return TempService;
});

我正在尝试从 startTimer 函数访问 checkTime 函数,但它抛出"TempService 不是函数"。在这种情况下如何处理范围?

你不需要调用 new TempService().getData()只需致电 TempService.getData()因为您要将对象作为参数传入,所以您应该已经有一个实例。

最新更新