16

I'm using arrow functions and I'm debugging with Chrome and Firefox Dev Tool. I am getting, this as undefined, even though the code still works.

For Example: When paused on the following breakpoint, I type this in the console, and it comes out undefined, even though the console.log shows the correct this:

class A {
    f = () => {
        debugger;
        console.log(this);
    };
}
new A().f();

My assumption is, that it has something to do with source-maps.

Here are the tools I use in order to build the my code:

  • webpack (devtool: eval)
  • babel-loader (es5 preset)
  • typescript-loader
Domi
  • 22,151
  • 15
  • 92
  • 122
Sebastian
  • 549
  • 1
  • 4
  • 14

2 Answers2

33

The problem is that the chrome debugger believes that the this in the source code refers to the run-time this, but this inside a arrow function in typescript source code is actually transformed to _this, so it's showing you the wrong object.

This is why it's only a problem in the debugger and the code still works fine. When I need to debug something where this is a problem, I just copy it to the console and prepend it with an underscore.

Dupocas
  • 20,285
  • 6
  • 38
  • 56
Alex
  • 14,104
  • 11
  • 54
  • 77
1

This might be an issue because JS arrow functions don't have this, the value of this might be referencing the object containing your arrow function, per Arrow functions revisited and MDN's article on Arrow function expressions

obsidian
  • 35
  • 4