最容易用代码解释:
##### 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。