Create A Copy Of A Module Instead Of An Instance In Node.js
Solution 1:
What you're doing is this (replacing your require()
call with what gets returned);
var new_game_obj = function() {
return game_logistics;
}
So, every time you call new_game_obj
, you return the same instance of game_logistics
.
Instead, you need to make new_game_obj
return a new instance of game_logistics
;
// room.js
function Game_Logistics() {
this.users = [];
this.return_users_count = function(){
return this.users.length;
};
}
module.exports = function() {
return new Game_Logistics();
}
This is quite a shift in mentality. You'll see that we're using new
on Game_Logistics
in module.exports
to return a new instance of Game_Logistics
each time it's called.
You'll also see that inside Game_Logistics
, this
is being used everywhere rather than Game_Logistics
; this is to make sure we're referencing the correct instance of Game_Logistics
rather than the constructor function.
I've also capitalized your game_logistics
function to adhere to the widely-followed naming convention that constructor functions should be capitalized (more info).
Taking advantage of the prototype chain in JavaScript is recommended when you're working with multiple instances of functions. You can peruse various articles on "javascript prototypical inheritance* (e.g. this one), but for now, the above will accomplish what you need.
Post a Comment for "Create A Copy Of A Module Instead Of An Instance In Node.js"