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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.