Reputation: 8143
There is a surprising behaviour with module.exports
. The following code:
module.exports = { test: 4};
module.exports.testMe = () => {console.log(this.test);};
Will output undefined
. But:
module.exports.test = 4;
module.exports.testMe = () => {console.log(this.test);};
Will output 4
. Why does it behave differently?
Upvotes: 0
Views: 29
Reputation: 106736
The reason has to do with how arrow functions work, they bind to this
(much like if you had used .testMe = fn.bind(this);
).
In the first case, you're overwriting module.exports
, but this
still points to the old object. So when testMe()
is implicitly bound to this
, you get undefined
because there was no test
property on the original module.exports
.
In the second case, you're not overwriting module.exports
, so module.exports === this
and testMe()
is implicitly bound to this
and outputs '4' as expected because both point to the same object, where test
exists.
Upvotes: 1