7

I`m using VS code and chrome debugger extension . The code below is executed without errors and produces the expected result, however i see that 'this' is undefined in WATCH section.

class Q {
    constructor() { 
        this.arr = [1,2,3]
    }
    log(e) {
        console.log(e)
    }
    test() {
        this.arr.forEach(e => {
            this.log(e); // this is undefined when debugging
        })
    }
}

const f = new Q().test()

what am I doing wrong?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
deemaagog
  • 81
  • 1
  • 5
  • Sounds like a Watch limitation rather than anything truly concerning. Does the code actually work? – Lightness Races in Orbit Feb 10 '18 at 16:13
  • Possible duplicate of [Value of "this" is incorrect when debugging Babel transpiled React with Chrome Devtools](https://stackoverflow.com/questions/36638663/value-of-this-is-incorrect-when-debugging-babel-transpiled-react-with-chrome-d) – Bergi Aug 26 '19 at 21:24

2 Answers2

7

To avoid conflicts with the this JavaScript keyword, TypeScript renames this into _this when transpiled. Try watching for _this instead.

BernardV
  • 1,700
  • 20
  • 15
  • This is certainly true, but it is inconvenient to set a watch on _this all the time when I want to see a variable value by hovering the mouse pointer. Any workaround to allow that? – Michael Witt Mar 13 '19 at 14:12
  • 1
    @Mike Witt: I don't know of any workaround to my workaround. Sorry – BernardV Mar 14 '19 at 13:59
  • Thanks Bernard that worked, however linting does still complain with `cannot find name _this.ts (2304)`. Do you know how to overcome that? – HostMyBus Sep 27 '19 at 09:37
  • 2
    To answer my own question add `let _this = this;` before referencing `_this` – HostMyBus Sep 27 '19 at 10:21
-2
class Q {

  arr = []

  constructor() { 
     this.arr = [1,2,3]
  }
  log(e) {
     console.log(e)
  }
  test() {
     this.arr.forEach(e => {
         this.log(e);
     })
  }
}

const f = new Q().test()
devrow
  • 86
  • 5