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

前端 未结 3 2021
粉色の甜心
粉色の甜心 2021-02-09 05:48

Easiest to explain with code:

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

showCount = function() {
 return console.log(count);
};
incC         


        
3条回答
  •  忘了有多久
    2021-02-09 06:11

    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

提交回复
热议问题