简体   繁体   中英

Using a require module in node.js as a class?

I am not quite sure how to do this correctly.

I have a module, game.js, which will contain all of the data about a game and its methods:

//game.js    
var players = [];

exports.add_player = function(player){
   players.push(player);
}
exports.get_players = function(){
   return players;
}
// etc etc

and

//game_handler.js
//this module would handle multiple games
var game_module = require('./game.js');
var games = [];
function create_game(){
  var game = new game_module();
  games.push(game);
  //here I would add some players and whatnot to the game
}

Is this how a good way to do it, or should I do a new require statement for ever new game I create?

var game = require('./game.js');

Its good how you do it.

Require() only read a file once in the newer nodejs-versions

You need to call var game = require('./game.js'); only once, then you can use it for each game you create

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM