我正在尝试使用一个脚本来共享“全局”变量的存储,而其他脚本可以要求该脚本查看这些变量,但这似乎不是正确的方法。
所以我有一个名为“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
}
显然,这不是正确的方法。我怎么能这样做?
更新
回答此问题所需的信息未包含在本文中。对于第二个例子,当它甚至没有运行一次时,它处于不同的范围,而“玩家”实际上意味着[]。我不接受正确答案,因为我所包含的所有信息都应该正常工作,因此无法解决问题。
答案 0 :(得分: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;
};
<强> run.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
答案 1 :(得分: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来实现这一点,以使其显然是全局的。
现在,无论你是否应该这样做,这是另一个问题。