Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - `this` is undefined in Dev Tools when using arrow function

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...