使用箭头功能时,在开发工具中未定义`this` [英] `this` is undefined in Dev Tools when using arrow function
问题描述
我正在使用箭头功能,并且正在使用Chrome和Firefox开发工具进行调试.我得到的是this
未定义,即使代码仍然可以工作.
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.
例如:在以下断点处暂停时,我在控制台中键入this
,即使console.log
显示正确的this
,它也会显示为undefined
:
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)
- typescript-loader
推荐答案
问题是chrome调试器认为源代码中的this
引用了运行时this
,但其中的this
打字稿源代码中的箭头功能实际上已转换为_this
,因此它向您显示错误的对象.
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.
这篇关于使用箭头功能时,在开发工具中未定义`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!