Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"this" keyword in nodejs does'nt get update when you export new object

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading