使用箭头功能时将其定义为未定义 [英] Getting this as undefined when using arrow function

查看:164
本文介绍了使用箭头功能时将其定义为未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用箭头功能,我正在使用Chrome和Firefox Dev Tool进行调试。我得到了,这个未定义,即使代码仍然有效。

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.

我的假设是,它与源地图有关。

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 ,所以它显示错误的对象。

The problem is that the chrome debugger believes that the this in the source code refers to the rune-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.

这篇关于使用箭头功能时将其定义为未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆