节点模块 – 导出一个variables与导出引用它的函数?
最简单的解释代码:
##### 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
exports
为count
的值。 即0。
一切都是通过价值传递的。
如果你把count
定义为这样的getter:
Object.defineProperty(exports, "count", { get: function() { return count; } });
然后exports.count
将总是返回当前的count
,因此是11
纠正我,如果我错了,但数字是不可变的types。 当你改变count
数值时,你的参考值也会改变。 所以exports.count
引用旧的count
数值。
在JavaScript中,函数和对象(包括数组)通过引用分配给variables,string和数字按值赋值 – 即通过复制。 如果var a = 1
且var b = a
和b++
,则a
仍然等于1。
在这一行上:
exports.count = count; // let's also export the count variable itself
你做了一个countvariables的副本。 setCount(),incCount()和showCount()操作都在闭包内的countvariables上运行,所以m.count不会再被触摸。 如果这些variables在this.count上运行,那么你会得到你期望的行为 – 但是你可能不想导出countvariables。