最容易用代码解释:
##### 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
导出的函数按预期工作.但我不清楚为什么m.count也不是11.
解决方法
exports.count = count
您在对象上设置属性计数导出为count的值.即0.
一切都是通过价值而不是通过参考传递.
如果你将count定义为这样的getter:
Object.defineProperty(exports,"count",{ get: function() { return count; } });
然后exports.count将始终返回count的当前值,因此为11