0

I am studying how exports and module.exports differ in Node. This question was particularly useful: module.exports vs exports in Node.js. In short... this is what happens:

//require function

module = {
   exports:{}
}

(function(exports){
    exports = 1; //contents of module
})(module.exports)

If you forget about the node, and just write a simple function with the same functionality:

newmodule = {exports:{}};
function reassign(exports){
    exports = ()=>{console.log("123")}
    //or exports = 1;
    //or exports = "Hello";
}

reassign(newmodule.exports)
console.log(newmodule.exports) // prints empty object, reassign failed

You can observe that newmodule.exports indeed never gets reassigned. Not sure if I am having a brain freeze, but newmodule.exports was passed by reference. Yet, reassigning is not reflected on the passed object newmodule.exports. Why is that?

Extending the passed object works as expected

function reassign(exports){
    exports.somefunc = ()=>{console.log("123")} // works as expected
}
sanjihan
  • 5,592
  • 11
  • 54
  • 119
  • 2
    "*was passed by reference*" no, it wasn't. It's [passed by value](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language?rq=1) but the value of the object is its reference. – VLAZ Apr 25 '19 at 07:41
  • why isn't `exports` in `exports = ()=>console.log("123")` the same as `newmodule.exports`? Thats why I passed it in – sanjihan Apr 25 '19 at 07:43
  • It *is* the same, but if you reassign the value you don't affect the original object. – VLAZ Apr 25 '19 at 07:43
  • If you reassign `exports`, it won't affect the original object. `var a = {}; var b = a; a = null` <- This won't set `b` to null. But, `var a = {}; var b = a; a.prop = 1`. Here `b` also gets `prop` because they are both pointing to the same object – adiga Apr 25 '19 at 07:44
  • thanks. that was unexpected, but it makes sense now – sanjihan Apr 25 '19 at 08:02

0 Answers0