Weird behavior when compiling "this", possible bug?


I like functional programming and so I often inject this into a function using bind:

const processA = (fn, b) => {
 this.a = fn(this.a, b)
 return this

however, this will be compiled to:

var processA = function processA(fn, b) {
  undefined.a = fn(undefined.a, b);
  return undefined;

This is quite irritating. See example code in the online REPL.

Did I miss something important or should I open an issue on phabricator for this?


This is how arrow-functions work. Each arrow function borrows the execution context from its outer lexical scope. Because you defined this particular arrow function at the top level (it is not wrapped in a function), this transpiles to undefined.

To get what you want, use function (fn, b) { instead of (fn, b) => {.


… but the expected behavior is that “this” will take on the window context. That is how Chrome and Firefox behave. Here is a screen shot of Chrome (as of Feb 2017) and it shows the arrow notation behavior I’m talking about.

Babel and JSFiddler have this ‘undefined’ behavior. Plunkr, Chrome and Firefox do not.