Thursday, February 16, 2017

ES6 Arrow Notation 'this' Scope Bug with FiddleJS

I just ran into an interesting bug. I've been ramping up on ReactJS and as part of that, one of our senior devs recommended that I get a handle on ECMAScript 6. He pointed me to a nice ECMAScript 6 course on Pluralsight that I really enjoyed.

One of the exercises explored the "this" behavior inside arrow notation and how it differs from behavior within traditional function definitions.
'use strict';
var price = 5.99, quantity = 10;
var productView = {
   price : 9.99,
      quantity : 10,
      traditionalFunction() {
        return this.price;
      arrowNotation : () => this.price

console.log('Traditional Notation ', productView.traditionalFunction());
console.log('Arrow Notation ', productView.arrowNotation());

In JSFiddle, the traditional notation returned the expected result (9.99), but the arrow notation says 'undefined' instead of 5.99.

Running this same code in Chrome or Firefox (or even Plunkr) worked fine!

I thought maybe I needed to add babel to pre-compile down to ES5, but according to the babel website, JSFiddle already runs it for you. I'm not at all familiar with Babel, but the Babel "Try It Out" tool translates the arrow notation into the traditional notation, but swaps "undefined" for this.

Ah-ha! It turns out Babel _is_ the problem. The 'undefined' message is Babel's behavior. Apparently someone else noticed this almost a year ago (Mar 2016), but it wasn't addressed in the forum. I added my two cents and the screen shots above to the thread. When I have more time, I'll dig around to find the bug reporting channels.

No comments:

Post a Comment