使用箭头函数时,在开发工具中未定义 `this` [英] `this` is undefined in Dev Tools when using arrow function
问题描述
我正在使用箭头函数,并且正在使用 Chrome 和 Firefox Dev Tool 进行调试.我得到,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
,它会出现 undefined
,即使 console.log
显示正确的this
:
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(开发工具:eval)
- babel-loader(es5 预设)
- 打字稿加载器
推荐答案
问题是chrome调试器认为源码中的this
是指运行时this
,但是 typescript 源代码中箭头函数中的 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屋!