对象在匿名函数中被认为是未定义的,但在它之前不是

时间:2016-10-09 19:13:56

标签: javascript node.js

我必须首先否认我正在修改Game Dev Tycoon,但游戏的来源是预先运行的,在此代码运行之前将“Game”对象放在全局范围内。

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;
})();

任何人都有任何关于为什么会失败的想法?

1 个答案:

答案 0 :(得分:3)

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

所以你:

  1. 创建一些局部变量,所有变量都以undefined
  2. 开头
  3. Gameundefined,因为您刚宣布它)的值复制到oldGameConst
  4. 由于上述原因,请尝试阅读oldGameConst.prototype ... undefined
  5. 如果您想从更广泛的范围访问Game请勿使用var 屏蔽它。