Spartan322 Spartan322 - 1 month ago 6
Node.js Question

Object is considered undefined in anonymous function but not before it

I must first disclaim I am modding Game Dev Tycoon, however the source of the game is run beforehand, putting a 'Game' object in global scope before this code runs.

new Game({
conferenceHype: 0
}).gameSize; /* proves that it exists */
(function() {
var Game, oldGame, oldGameConst;
oldGameConst = Game;
oldGame = oldGameConst.prototype; /* fails here because it thinks oldGameConst is undefined */
Game = function(company) {
oldGameConst.call(this, company);
this.company = company;
};
Game.prototype = oldGame;
})();


Anyone have any ideas on why this would fail?

Answer
  var Game, oldGame, oldGameConst;
  oldGameConst = Game;
  oldGame = oldGameConst.prototype; /* fails here because it thinks oldGameConst is undefined */

So you:

  1. Create some local variables, all of which start out as undefined
  2. Copy the value of Game (undefined because you just declared it) to oldGameConst)
  3. Try to read oldGameConst.prototype … which is undefined for the above reasons.

If you want to access Game from the wider scope: don't mask it with var.