Home > other >  Why is this property showing up undefined in angular?
Why is this property showing up undefined in angular?

Time:09-25

I can't seem to figure out why the first console.log is displaying the parameter correctly but the second shows undefined.

Console Log Output:

text
undefined

Code:

ngOnInit() {
this.getPuzzle();
}
    getPuzzle() {
    this.restProviderService.getPuzzle(this.gameService.getGameId()).subscribe(puzzle => {
      this.puzzleType = puzzle.type;
      this.puzzleValue = puzzle.value;

      console.log(this.puzzleType);

      setTimeout(this.handlePuzzle , 3000);
    });
  }
    
      handlePuzzle() {
          console.log(this.puzzleType);
          if (this.puzzleType == 'text') {
            new Vara("#text", "assets/fonts/vara/Satisfy/SatisfySL.json", [{
              text: 'hello',
              delay: 2000,
              x: 2
            }], {
              fontSize: 25,
              strokeWidth: 1.5,
              duration: 5000,
              color: "black"
            });
          }
        
    
      }

CodePudding user response:

When you pass the function this.handlePuzzle to setTimeout the this representing your class is lost, and handlePuzzle receives the setTimeout's this instead.

Use an arrow function instead of passing the function itself:

setTimeout(() => this.handlePuzzle(), 3000);

CodePudding user response:

Inside JS event listeners this refers to the event target. But inside the handlePuzzle method (sort of an event listener), you need this to refer to the current object instance (as usual in a method).

You have 2 solutions:

  • Use an arrow callback. Arrow callbacks preserve the value of this.

    setTimeout(()=>this.handlePuzzle(), 3000)

    or in your method declaration

    handlePuzzle=()=> { console.log(this.puzzleType);

  • Use bind to set the value of this.

    setTimeout(this.handlePuzzle.bind(this), 3000);

    or, in the constructor

    this.handlePuzzle = this.handlePuzzle.bind(this);

For more details, refer to the following article. https://dev.to/alexdevero/a-quick-guide-to-this-keyword-in-javascript-what-this-is-and-when-7i5

  • Related