Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript global variable undefined in function scope

I am new to JavaScript and trying to make a simple node server. Here is my code:

var activeGames = {}

exports.initialize = function(){
    var gameID = "game12345"
    activeGames.gameID = new Game(gameID, "player1", "player2")
}

I call the initialize function from another module, and I get an error stating that activeGames is undefined. activeGames is at the outermost scope of the file. I tried adding 'this' before activeGames.gameID but that did not fix it. Why is activeGames undefined? Thanks in advance.

EDIT: Here's how I'm calling this code.

In my base index file I have

const handler = require("./request-handler.js")
handler.initialize()

In request-handler.js, I have

var gameManager = require('./game-manager')

exports.initialize = function(){
    gameManager.initialize()
}
like image 973
Connor Avatar asked Jul 17 '26 12:07

Connor


1 Answers

JavaScript has lexical scope, not dynamic scope. ref: https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping

Lexical scope means that whether a variable is accessible or not depends on where they appear in the source text, it doesn't depend on runtime information.

example:

function foo() {
  var bar = 42;
  baz();
}

function baz() {
  console.log(bar); // error because bar is not in the scope of baz
}

the same problem happens in your code,

var activeGames

is not in scope.

try this variation:

exports.initialize = function(){
    var activeGames = {}
    var gameID = "game12345"
    activeGames.gameID = new Game(gameID, "player1", "player2")
}

A good solution could be to use a class and export it: --THIS CODE IS NOT TESTED--

class gamesManager {
   var activeGames = {}

   initialize() {
      var gameID = "game12345"
      activeGames.gameID = new Game(gameID, "player1", "player2")
   }
}

exports.gamesManager = gamesManager

USE:

const activeGames = require('./game-manager');
const activeGamesInstance = new activeGames.gamesManager();
activeGamesInstance.initialize();
like image 58
Danilo Calzetta Avatar answered Jul 20 '26 02:07

Danilo Calzetta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!