I started a new Backbone/Marionette application this week, and decided to put Babel in place so I can use ES6 features (if you want an introduction to Babel / ES6 features, check out my WatchMeCode series on ES6). I honestly wasn’t sure what benefit I would get, at first. I’ve been playing with ES6 for a while now, but have not yet found the “AHA!” moment that makes me really want to use it everywhere.
What I have found, however, is a subtle benefit of using arrow functions with Backbone/Marionette, that makes me smile every time.
Managing “this” With Arrow Functions
One of the nice features of arrow functions is the ability to manage “this” in the function being executed. Arrow functions use lexical scoping to ensure “this” is maintained based on the context of the function being called (see this WatchMeCode episode on arrow functions for more details).
In short, that allows me to take this Backbone/Marionette code:
and turn it in to this:
The difference is small… it’s a bit subtle, if you’re not looking for it. But it’s right there on line 5.
Subtle, And Important