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?