Reputation: 137
I am a newbie in nodejs.
I have this Script: book.js
var page = 0;
exports.setPageCount = function (count) {
page = count;
}
exports.getPageCount = function(){
return page;
}
Along with the follownig script: 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());
The Output I get:
Book A Pages : 20
Book B Pages : 20
So, I modified script:
module.exports = function(){
var page = 0;
setPageCount : function(count){
page = count;
},
getPageCount : function(){
return page;
}
}
I am expecting the following output:
Book A Pages : 10
Book B Pages : 20
But still getting the original outcome, does anyone have an idea where I made an error?
Upvotes: 1
Views: 843
Reputation: 1329
There are a few ways to go about this and your last attempt is almost a valid one -- modify your module like so:
module.exports = function() {
var pages = 0;
return {
getPageCount: function() {
return pages;
},
setPageCount: function(p) {
pages = p;
}
}
}
and your usage like so:
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());
Upvotes: 2