nodejscaching与module.exports问题
我是nodejs的新手。
我有这个脚本: book.js
var page = 0; exports.setPageCount = function (count) { page = count; } exports.getPageCount = function(){ return page; }
随着follownig脚本: scripts.js
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());