Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Modules - exporting a variable versus exporting functions that reference it?

Easiest to explain with code:

##### module.js
var count, incCount, setCount, showCount;
count = 0; 

showCount = function() {
 return console.log(count);
};
incCount = function() {
  return count++;
};
setCount = function(c) {
  return count = c;
 };

exports.showCount = showCount;
exports.incCount = incCount;
exports.setCount = setCount; 
exports.count = count; // let's also export the count variable itself

#### test.js
var m;
m = require("./module.js");
m.setCount(10);
m.showCount(); // outputs 10
m.incCount();  
m.showCount(); // outputs 11
console.log(m.count); // outputs 0

The exported functions work as expected. But I'm not clear why m.count isn't also 11.

like image 407
David EGP Avatar asked Sep 11 '11 22:09

David EGP


1 Answers

exports.count = count

Your setting a property count on an object exports to be the value of count. I.e. 0.

Everything is pass by value not pass by reference.

If you were to define count as a getter like such :

Object.defineProperty(exports, "count", {
  get: function() { return count; }
});

Then exports.count would always return the current value of count and thus be 11

like image 123
Raynos Avatar answered Nov 15 '22 00:11

Raynos