microsoft / microsoft/TypeScript

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

未关闭
#10,285 15 条评论 4 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Domain: lib.d.ts Good First Issue Help Wanted Suggestion
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

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.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先使用 TypeScript 1.8.10 重现该示例,并检查生成的 JavaScript,以区分编译器行为和 JavaScript 回调语义。该 issue 没有指明源文件或测试;要继续推进,需要确定预期结果是编译器诊断还是语言变更,然后为约定的行为添加覆盖。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, typescript
领域
compilers
Issue 类型
缺陷
难度
5/5
预计耗时
一周以上
活跃度
活跃
描述清晰度
需要澄清
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。