microsoft / microsoft/TypeScript
Scope of this is lost when passing a member function to setInterval
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.3k
- Merge medio
- 2 d 4 h
- PR fusionados (30 d)
- 132
Descripción
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.
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Empieza reproduciendo el ejemplo con TypeScript 1.8.10 e inspecciona el JavaScript generado para separar el comportamiento del compilador de la semántica de los callbacks de JavaScript. El issue no indica ningún archivo fuente ni ninguna prueba; para avanzar es necesario determinar si el resultado previsto es un diagnóstico del compilador o un cambio del lenguaje, y después añadir cobertura para el comportamiento acordado.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- javascript, typescript
- Área
- compilers
- Tipo de issue
- Error
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Activo
- Claridad
- Necesita aclaración
- Aptitud para principiantes
- 35/100