Javascript module.exports的节点缓存问题
我是nodejs的新手 我有一个脚本:Javascript module.exports的节点缓存问题,javascript,node.js,caching,module,export,Javascript,Node.js,Caching,Module,Export,我是nodejs的新手 我有一个脚本:book.js var page = 0; exports.setPageCount = function (count) { page = count; } exports.getPageCount = function(){ return page; } var bookA = require('./book'); var bookB = require('./book'); bookA.setPageCount(10);
book.js
var page = 0;
exports.setPageCount = function (count) {
page = count;
}
exports.getPageCount = function(){
return page;
}
var bookA = require('./book');
var bookB = require('./book');
bookA.setPageCount(10);
bookB.setPageCount(20);
console.log("Book A Pages : " + bookA.getPageCount());
console.log("Book B Pages : " + bookB.getPageCount());
与下面的脚本一起使用:scripts.js
var page = 0;
exports.setPageCount = function (count) {
page = count;
}
exports.getPageCount = function(){
return page;
}
var bookA = require('./book');
var bookB = require('./book');
bookA.setPageCount(10);
bookB.setPageCount(20);
console.log("Book A Pages : " + bookA.getPageCount());
console.log("Book B Pages : " + bookB.getPageCount());
我得到的输出:
Book A Pages : 20
Book B Pages : 20
所以,我修改了脚本:
module.exports = function(){
var page = 0;
setPageCount : function(count){
page = count;
},
getPageCount : function(){
return page;
}
}
我期望得到以下结果:
Book A Pages : 10
Book B Pages : 20
但是仍然得到最初的结果,有人知道我在哪里犯了错误吗 有几种方法可以做到这一点,而您的最后一次尝试几乎是有效的——按如下方式修改您的模块:
module.exports = function() {
var pages = 0;
return {
getPageCount: function() {
return pages;
},
setPageCount: function(p) {
pages = p;
}
}
}
var bookFactory = require('./book');
var bookA = bookFactory();
var bookB = bookFactory();
bookA.setPageCount(10);
bookB.setPageCount(20);
console.log("Book A Pages : " + bookA.getPageCount());
console.log("Book B Pages : " + bookB.getPageCount());
你的用法是这样的:
module.exports = function() {
var pages = 0;
return {
getPageCount: function() {
return pages;
},
setPageCount: function(p) {
pages = p;
}
}
}
var bookFactory = require('./book');
var bookA = bookFactory();
var bookB = bookFactory();
bookA.setPageCount(10);
bookB.setPageCount(20);
console.log("Book A Pages : " + bookA.getPageCount());
console.log("Book B Pages : " + bookB.getPageCount());
var bookA=bookFactory();^类型错误:bookFactory不是一个函数。您还可以选择从模块返回
类
或原型
,并使用新建
关键字。有很多方法可以实现你想要的。我编辑我的帖子也是为了反映你的模块的变化——太快地阅读你的第二次尝试,回顾过去,我意识到它也需要改变。抱歉。请运行您的代码,它显示了两个0 Book A页面:0 Book B页面:0因为调用时使用getPageCount,变量页面在顶部被零初始化感谢@daf,您是冠军