4

I'm just getting around to changing some of my code to ES6 and I ran across some code where the arrow function did not work and I am not sure I understand why. The code is from a plugin for Hapi to decorate the reply interface.

ES5:

server.decorate('reply', 'test', function(schema, response) {
  return this.response(mask(schema, response));
});

ES6:

server.decorate('reply', 'test', (schema, response) => {
  return this.response(mask(schema, response));
});

The E66 doesn't work and throws an error:

Uncaught error: this.response is not a function

Why is this?

cyberwombat
  • 38,105
  • 35
  • 175
  • 251
  • 1
    the arrow functions in ES6 automatically binds `this` to the outer scope, so it's not equivalent in this case. – Seiyria Nov 28 '15 at 03:40
  • 1
    I see - what wound be the answer? just leave it as `function`? – cyberwombat Nov 28 '15 at 03:40
  • 3
    Yes. There's not a lot you can do if `this` for that particular function is bound to something else. – Seiyria Nov 28 '15 at 03:41
  • Ok. Post an answer and I'll mark it. Thanks – cyberwombat Nov 28 '15 at 03:42
  • 2
    The difference in `this` behavior is in the very first paragraph of the relevant MDN page. By the way, correct terminology is "arrow function" (not "double arrow function"). –  Nov 28 '15 at 04:32

1 Answers1

6

In this particular case, the library is changing what this refers to inside the callback for decorate. When using arrow functions (=>), this is equivalent to the this of the outer scope. This means that you're basically stuck using function for this.

Seiyria
  • 2,112
  • 3
  • 25
  • 51