1

when i try to reassign module.exports , this still points to an empty object

module.exports  = {a:4}
console.log(this) // {}


however, when I add a new property to module.exports , this points to an object with the new property.

module.exports.a = 4
console.log(this) // {a:4}

why do i not get the same result in both cases?

2 Answers2

1

By default in a module, this points to the original exports object that the module system creates when it sets up your module. When you do:

module.exports = {a: 4}

You replace the existing exports property on the module object with a new and separate one. But, this still points at the original, empty exports object. So, when you do:

console.log(this);

after creating a new exports object, this is still pointing at the original exports object which you never modified. So, it still shows that object as being empty.

If, after reassigning the exports property with a new object like you did above, you then did this:

console.log(module.exports === this);            // false

You will see that this does not point at the new exports object you assigned as a property on the module object.


On the other hand, when you do this:

module.exports.a = 4

You are not replacing the existing exports object. Instead, you're just adding a property to the existing object, so the object you modified is the original exports object that this still points to.

jfriend00
  • 580,699
  • 78
  • 809
  • 825
1

As per https://stackoverflow.com/a/22771432/7878410

When JavaScript files are required as Node modules, the Node engine runs the module code inside of a wrapper function. That module-wrapping function is invoked with this set to module.exports.

Hence, module.exports and this are pointing to the same object which is {} when you do the following,

module.exports  = {a:4}
console.log(this) // {}

module.exports starts to point to a new object which is {a:4} whereas this still points to the previous object which is {}.

But, when you do the following,

module.exports.a = 4
console.log(this) // {a:4}

You end up updating the object to which module.exports as well as this are pointing. Hence, this returns {a:4}