1

I'm facing a bug in a program where I decided to use the ES6 ways to declare a function.

const fun = () => { }

And I've always thought this was the exact equivalent of

const fun = function() {}

In my code it's a little bit more complicated than that, here are the 2 exact pieces of code

# works as intended
const updateQuery = function (
  previousResult,
  {
    subscriptionData: {
      data: { subscribeToCurrentIdentity: { currentIdentity } }
    }
  }
) {
  delete currentIdentity['__typename']
  this.currentIdentityInput = currentIdentity
}

And with fat arrows

# breaks in the middle
const updateQuery = (
  previousResult,
  {
    subscriptionData: {
      data: { subscribeToCurrentIdentity: { currentIdentity } }
    }
  }
) => {
  delete currentIdentity['__typename']
  this.currentIdentityInput = currentIdentity
}

The error is pretty straight forward as this seems to be undefined with the () => {} methodology.

bundle.esm.js?4518:798 TypeError: Cannot set property 'currentIdentityInput' of undefined

So I decided to check what happens at compilation, here's the compiled code

# working code
"use strict";

var updateQuery = function updateQuery(previousResult, _ref) {
  var currentIdentity = _ref.subscriptionData.data.subscribeToCurrentIdentity.currentIdentity;
  delete currentIdentity['__typename'];
  this.currentIdentityInput = currentIdentity;
};

And the other way

# breaking code
"use strict";

var _this = void 0;

var updateQuery = function updateQuery(previousResult, _ref) {
  var currentIdentity = _ref.subscriptionData.data.subscribeToCurrentIdentity.currentIdentity;
  delete currentIdentity['__typename'];
  _this.currentIdentityInput = currentIdentity;
};

The difference is pretty obvious, instead of taking this it sets a _thiswhich I do not understand. Can someone tells me why both ways are different on this matter? How does it work when it compiles?

Laurent
  • 2,284
  • 2
  • 21
  • 41

0 Answers0