i have this code in nodejs (commonjs) v14.16.1
module.exports.varOne = 'one'
module.exports = {varTwo: 'two', ...module.exports}
console.log('module', module);
console.log(this, this === module.exports);
and this is the results after running it
module Module {
id: '.',
path: '...',
exports: { varTwo: 'two', varOne: 'one' },
parent: null,
filename: '...',
loaded: false,
children: [],
paths: [...]
}
{ varOne: 'one' } false
I don't understand why "this" here doesn't change to the new exports? please help.
CodePudding user response:
In Javascript, the value of this
doesn't change within a given code context like this. That's how the language itself works.
You replaced the given exports
object with a different object. Nothing in the language will cause that assignment to change the value of this
. The value of this
still points at the original exports
object.
Fortunately, this isn't a problem in nodejs as you have multiple work-arounds. You can either not replace the exports
object (just assign values to the existing one) or you can use module.exports
to refer to the new object instead of this
.
FYI, you will notice the same thing with the exports
variable. It will still point at the original exports object too.