Microsoft/TypeScript

Scope of this is lost when passing a member function to setInterval

Open

#10,285 建立於 2016年8月11日

在 GitHub 查看
 (12 留言) (4 反應) (0 負責人)TypeScript (6,726 fork)batch import
Domain: lib.d.tsGood First IssueHelp WantedSuggestion

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 PR)

描述

TypeScript Version: 1.8.10

When passing a member function to setInterval, the scope of 'this' is lost within the callback, though the structure of the code (given experience of any object orientated language) indicates it shouldn't be.

Example code

export class SetIntervalTest {
  private someNumber: number = 1;

  trigger() {
      setInterval(this.setIntervalCallback, 400);
  }

  private setIntervalCallback() {
      console.log(this.someNumber);
  }
}  

Expected behavior When console.log(this.someNumber); is called, the scope of this is within the scope of the SetIntervalTest interval instance, printing '1'.

Actual behavior: The scope of this is pulled from global scope, resulting in this.someNumber being 'undefined'. If that isn't possible, the compiler should indicate the expected behaviour is not what you're going to get.

To fix this i need to change 'setInterval(this.setIntervalCallback, 400);' to 'setInterval(() => this.setIntervalCallback(), 400);' so 'this' is correctly scoped in the callback.

貢獻者指南