Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 in Chrome - Babel Sourcemaps and Arrow Functions lexical scope

I have a function inside a ES6 class:

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

Babel transpiles this to a different form and it generates a _this variable to control the lexical scope of the arrow function.

var _this = this;

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

When i debug the ES6 class using sourcemaps in Chrome and put a breakpoint on the line where i call this.actions.setEvents(data); i noticed that Chrome does not "re-map" this to match the original ES6 code, but instead this points to the outer function scope and i need to use _this if i want to access the arrow function lexical scope, which is completely pointless. If i am using sourcemaps i would expect Chrome dev. tools to preserve the lexical scope of this as in my ES6 code.

Is there a way to make Chrome developer tools work as expected with sourcemaps and arrow functions?

like image 812
Faris Zacina Avatar asked Aug 31 '15 17:08

Faris Zacina


People also ask

Does arrow function keep lexical scope?

While in ES5 'this' referred to the parent of the function, in ES6, arrow functions use lexical scoping — 'this' refers to it's current surrounding scope and no further. Thus the inner function knew to bind to the inner function only, and not to the object's method or the object itself.

What does => mean in ES6?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

Are arrow functions ES6?

Introduction. The 2015 edition of the ECMAScript specification (ES6) added arrow function expressions to the JavaScript language. Arrow functions are a new way to write anonymous function expressions, and are similar to lambda functions in some other programming languages, such as Python.

When should I use arrow functions in ES6?

When you should use them. Arrow functions shine best with anything that requires this to be bound to the context, and not the function itself. Despite the fact that they are anonymous, I also like using them with methods such as map and reduce , because I think it makes my code more readable.


1 Answers

Well,

  1. Chromium doesn't utilize the mappings from names currently. https://code.google.com/p/chromium/issues/detail?id=327092

  2. this is a special binding, so the way it's transpiled it wouldn't be possible to do that. The only thing I can think of would be transpiling it like this, but I don't know if it's viable:

    $.get('/api/v1/events', function (data) {
      this.actions.setEvents(data);
    }.bind(this));
    
like image 75
JMM Avatar answered Oct 11 '22 11:10

JMM