0

我正在尝试使用一个脚本来公共存储“全局”变量,而其他脚本可能需要该脚本来查看这些变量,但这似乎不是正确的方法。

所以我有一个名为“gamedata.js”的脚本,如下所示:

var players = {};
exports.players = players;

在一个脚本中:

var gamedata = require('./gamedata');
var players = gamedata.players;
players[player_id] = new player(. . .);
for (var pid in players){
    console.log(pid + ' is online.'); // This runs correctly
}

然后,稍后,在另一个脚本中(我知道这是稍后的;它实际上是在一个循环中)。

var gamedata = require('./gamedata');
var players = gamedata.players;
for (var pid in players){
    // Doesn't even run once
}

显然这不是正确的方法。我怎么能做这样的事情?

更新:

回答此问题所需的信息未包含在此帖子中。对于第二个示例,当它甚至没有运行一次时,它处于不同的范围内,而“玩家”实际上意味着 []。我不接受对此的正确答案,因为我包含的所有信息都应该正常工作,因此无法找到解决方案。

4

2 回答 2

4

不要尝试在 node.js 中使用全局变量。另请注意,require它将引用一个缓存的对象,并且实际上不会多次重新要求同一个文件。

这是一个非常通用的示例,说明如何在不使用全局变量的情况下开始设置纸牌游戏

lib/deck.js

var SUITS = ["H", "C", "D", "S"],
    RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

var Deck = module.exports = function Deck() {
  this.cards = [1, 2, 3, ..., 52];
  this.shuffle();
};

Deck.prototype.shuffle = function shuffle() {
  // shuffle this.cards
};


Deck.prototype.dealCard = function dealCard() {
  var id = this.cards.shift();
  return {id: id, rank: RANKS[id%13], suit: SUITS[id%4]};
};

lib/game.js

var Deck = require("./deck");

var Game = module.exports = function Game(numCards) {
  this.numCards = numCards;
  this.deck = new Deck();
};

Game.prototype.dealCards = function dealCards(player) {
  for (var i=0; i<this.numCards; i++) {
    player.cards.push(this.deck.dealCard());
  }
};

// ...

lib/player.js

var EventEmitter = require("events").EventEmitter;

var Player = module.exports = function Player(name) {
  this.name = name;
  this.cards = [];
};

Player.prototype = Object.create(EventEmitter.prototype, {constructor: {value: Player}};

// ...

lib/session.js

var EventEmitter  = require("events").EventEmitter,
    Game          = require("./game"),
    Player        = require("./player");

var Session = module.exports = function Session(numCards) {
  EventEmitter.call(this);
  this.game = new Game(numCards);
  this.players = [];
  this.scores = [];
};

Session.prototype = Object.create(EventEmitter.prototype, {constructor: {value: Session}});

Session.prototype.addPlayer = function addPlayer(player) {
  // add the player
  this.players.push(player);

  // deal the player some cards
  this.game.dealCards(player);

  // setup event listeners
  player.on("score", function(points) {
    this.addScore(player, points);
  });

  player.on("playerTurn", function(event) {
    // ...
  });
};

Session.prototype.addScore = function(player, points) {
  if (this.scores[player.id] === undefined) {
    this.scores[player.id] = 0;
  }
  this.scores[player.id] += points;
};

运行.js

var Session  = require("./session"),
    numCards = 2;

var sessionInstance = new Session(numCards);

sessionInstance.on("addPlayer", function(player) {
  this.addPlayer(player);
});

// e.g.,
// setup a net.Server and fire "addPlayer" when a user connects
于 2013-08-15T00:06:53.280 回答
0

完成您尝试做的事情的一种方法是使用单例类型对象作为您的“全局”内存空间,假设该文件名为 NodeGlobalVars.js。

exports.NodeGlobalVars = NodeGlobalVars;

function NodeGlobalVars()
{   
    //only do this if this is the first time the object has been used
    if(typeof(NodeGlobalVars.SingleInstance) === "undefined")
    {
        this.GlobalVariable1 = 1;
        this.GlobalVariable2 = 2;

        //set to this so we won't create more objects later
        NodeGlobalVars.SingleInstance = this;
    }

    return NodeGlobalVars.SingleInstance;   //return the single instance variable
};

现在,在您想要从中获取数据并对其进行修改的其他文件中,您可以根据需要在任意多个不同的文件中执行以下操作:

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

//now get access to the NodeGlobalVars
var Globals = new NodeGlobalVars();

//now log the state of GlobalVariable1 and modify the value of GlobalVariable2
console.log("Global1: " + Globals.GlobalVariable1);
Globals.GlobalVariable2++;

您可以从任何其他文件自由修改数据,它们都将指向同一内存。实际上,您已经为节点应用程序创建了全局内存空间,并在其前面使用了一个非常方便的名称空间 Globals,以使其明显是全局的。

现在,你是否应该这样做,这是另一个问题。

于 2013-08-15T14:34:24.140 回答