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?
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.
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.
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 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.
Well,
Chromium doesn't utilize the mappings from names
currently. https://code.google.com/p/chromium/issues/detail?id=327092
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With