0

I have a property defined but when I try to access it from inside a setInterval anonymous function, it is not being recognized.

  this.game.seconds = 6;
  useTimer() {
    let timer = setInterval(
      function () {
        this.game.seconds--;//here the keyword this is not being recognized
      }, 1000
    );
  }
gsamaras
  • 71,951
  • 46
  • 188
  • 305
user3646717
  • 1,095
  • 2
  • 12
  • 21
  • 2
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Yury Tarabanko Sep 24 '17 at 06:52
  • 1
    Hint: it is because you are **not** using arrow function – Trash Can Sep 24 '17 at 06:52
  • This has nothing to do with TypeScript. The language you are programming in is called "JavaScript". TypeScript is merely a thin typing layer on top of JavaScript. TypeScript introduces no new semantics for `this`; indeed, it introduces no new execution semantics whatsoever. –  Sep 24 '17 at 07:26

2 Answers2

1

The problem occurs because you are not not using an Arrow Function.

Arrow functions take this from their outer execution context.

The ref mentions:

arrow functions which do provide their own this binding (it remains the this value of the enclosing lexical context).

Read more in No Binding of this.

So just to this instead:

let timer = setInterval(
  () => {
    this.game.seconds--; // 'this' takes its value from the outer context
  }, 1000
);
gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

Well I could fulfill my goal with arrow functions as commented by Dummy and answered by gsamaras:

  this.game.seconds = 6;
  useTimer() {
    let timer = setInterval(
      () => {
        this.game.seconds--;
      }, 1000
    );
  }

more info here.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
user3646717
  • 1,095
  • 2
  • 12
  • 21