javascript - Chrome 中的 ES6 - Babel Sourcemaps 和 Arrow Functions 词法作用域

标签 javascript google-chrome ecmascript-6 babeljs source-maps

我在 ES6 class 中有一个函数:

class Test {
   // Omitted code for brevity
   loadEvents() {
      $.get('/api/v1/events', (data) => {
         this.actions.setEvents(data);
      });
   }
}

Babel 将 this 转换为不同的形式,并生成一个 _this 变量来控制箭头函数的词法范围。

var _this = this;

$.get('/api/v1/events', function (data) {
   _this.actions.setEvents(data);
});

当我在 Chrome 中使用源映射调试 ES6 类并在我调用 this.actions.setEvents(data); 的行上放置断点时,我注意到 Chrome 没有“重新映射” this 来匹配原始的 ES6 代码,但是 this 指向外部函数范围,如果我想访问函数,我需要使用 _this箭头函数词法范围,这是完全没有意义的。如果我使用的是 sourcemaps,我会期待 Chrome dev。保留 this 词法范围的工具,就像在我的 ES6 代码中一样。

有没有办法让 Chrome 开发者工具与 sourcemaps 和箭头函数一起按预期工作?

最佳答案

嗯,

  1. Chromium 目前不使用来自 names 的映射。 https://code.google.com/p/chromium/issues/detail?id=327092

  2. this 是一个特殊的绑定(bind),因此它的转译方式不可能做到这一点。我唯一能想到的就是像这样转译它,但我不知道它是否可行:

    $.get('/api/v1/events', function (data) {
      this.actions.setEvents(data);
    }.bind(this));
    

关于javascript - Chrome 中的 ES6 - Babel Sourcemaps 和 Arrow Functions 词法作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32316571/

相关文章:

jquery - 我网站上的垂直线 CSS + 滚动

java - Selenium 编程 -- 按 F12,现在如何从 Chrome 复制粘贴代码?

javascript - 父节点上的事件监听器也在所有子节点上触发

javascript - jQuery 事件处理程序

javascript - 在 JavaScript 中克隆对象的解耦版本

javascript - 当我运行这段代码时,元 slider 消失了

javascript - 该功能在 chrome 中运行良好,但在 IE 和 Firefox 中运行不佳

javascript - 在 Jest : done() not being called as expected 中测试异步代码

google-chrome - 语法错误 : missing = in const declaration Firefox 50

javascript - 使用扩展运算符并组合参数