1

Just for context, not important: I'm using this code to replicate some behavior in a Node.js/Express controller action for use in testing with Mocha. I'm returning the value of this from the status method for the purpose of method chaining (res.status(200).json() is used in the controller action), so the json method can be called on res, since it's an Express method on the response object.

It seems from my Mocha test run that the value of this (the res object) is correctly returned in the first snippet, in which I use ES6 concise method syntax to return this, but not the second code snippet, where I try to use an arrow function to implicitly return this. I thought using an arrow function would have the same result, since in arrow functions, the value of this is the enclosing lexical scope (seemingly the res object in this case).

Works as expected; res is seemingly returned as value of status method call

const res = {
  status() {
    return this;
  },
  json: () => {},
};

Doesn't work as expected (res seemingly not returned as value of this for status method call):

const res = {
  status: () => this,
  json: () => {},
};

Why doesn't () => this return the enclosing object?

Deja
  • 3,278
  • 2
  • 18
  • 46
  • 2
    "*in arrow functions, the value of `this` is the enclosing lexical scope*" - not exactly, it's the value of the `this` value in the enclosing lexical scope. "*seemingly the `res` object in this case*" - no, the object literal (even if "enclosing the arrow expression") does not form a lexical scope. – Bergi Jul 19 '20 at 21:21

1 Answers1

1

Ciao according to MDN docs:

In arrow functions, this retains the value of the enclosing lexical context's this. In global code, it will be set to the global object:

var globalObject = this;
var foo = (() => this);
console.log(foo() === globalObject); // true

So basically write () => this and this in arrow function is the same thing.

Giovanni Esposito
  • 5,165
  • 1
  • 5
  • 23