无法读取undefined的属性'[function]'

时间:2017-09-09 01:02:42

标签: javascript typescript ionic-framework ionic2

我在home.ts课程中使用Ionic 2.2.1在Typescript中写作。

我收到错误: TypeError:this.GetLocalInformation不是函数 执行。

以下是这两个功能的相互作用:

  ngOnInit() {
this.GetLocalInformation(); //sets this.school to the school
this.fullSchedule = this.schedProvider.GetCorrespondingSchool(this.school);
this.fullSchoolName = this.schedProvider.GetFullSchoolName(this.school);


this.timerFunc(); //Timer Function -- This method is in a loop with itself
}

timerFunc() { //Self Updating Timer Method
this.GetLocalInformation();
this.periods = this.schedProvider.GetPeriod(this.school);
this.timeInSeconds = ((this.periods[0].h * 3600) + (this.periods[0].m * 60)) - (new Date().getHours() * 3600 + new Date().getMinutes() * 60) - new Date().getSeconds(); //Calculate time difference
this.currentP = this.periods[0].title;
this.nextP = this.periods[1].title;

var dt = Date.now() - this.expected; // the drift (positive for overshooting)
if (dt > this.interval) {
  // something really bad happened. Maybe the browser (tab) was inactive?
  // possibly special handling to avoid futile "catch up" run
}
//Set Variables

//Update Timer
//this.timer.timer.secondsRemaining = +this.timeInSeconds;
this.timer.updateTimer(this.timeInSeconds);
this.expected += this.interval;
setTimeout(this.timerFunc, Math.max(0, this.interval - dt)); // take into account drift
}

我在 timerFunc()的第一行收到错误,这没有任何意义,因为我在 ngOnInit()

中完全调用了相同的函数

1 个答案:

答案 0 :(得分:4)

当您将this传递到this.timerFunc函数时,您的setTimeout上下文将丢失。要正确绑定范围,您可以使用.bind(this)

setTimeout(this.timerFunc.bind(this), Math.max(0, this.interval - dt)

或使用箭头功能自动绑定this

setTimeout(() => this.timerFunc(), Math.max(0, this.interval - dt))