使用 TypeScript 0.9.1.1,当尝试从另一个模块/文件访问静态变量时,它是未定义的。
示例代码:
应用程序.ts:
import Game = require('Game');
var game = new Game();
游戏.ts:
import Grid = require('Grid');
class Game
{
public Grid: Grid;
public static Game: Game;
constructor()
{
Game.Game = this;
this.Grid = new Grid();
this.Grid.SeeIfStaticWorks();
}
}
export = Game;
网格.ts:
import Game = require('Game');
class Grid
{
public SeeIfStaticWorks()
{
var shouldNotBeUndefined = Game.Game;
}
}
export = Grid;
Game.Game
调用前检查this.Grid.SeeIfStaticWorks();
显示它已定义:
但是当试图从内部访问它时,SeeIfStaticWorks()
它是未定义的:
问题是:如何能够从其他模块访问静态变量?
更新:
从一个文件运行所有代码允许跨模块使用静态变量(此处为演示):
class Grid
{
public SeeIfStaticWorks()
{
console.log(Game.Game);
if (Game.Game)
alert('Instance is defined!');
else
alert('Instance is undefined!');
}
}
class Game
{
public Grid: Grid;
private static game : Game;
public static get Game() : Game
{
if (this.game == null)
{
this.game = new Game();
}
return this.game;
}
constructor()
{
this.Grid = new Grid();
}
}
var game = Game.Game;
game.Grid.SeeIfStaticWorks();
如果我对 AMD RequireJS 使用相同的逻辑,则调用时静态变量未定义SeeIfStaticWorks()
:
应用程序.ts:
import Game = require('Game');
var game = Game.Game;
game.Grid.SeeIfStaticWorks();
游戏.ts:
import Grid = require('Grid');
class Game
{
public Grid: Grid;
private static game : Game;
public static get Game() : Game
{
if (this.game == null)
{
this.game = new Game();
}
return this.game;
}
constructor()
{
this.Grid = new Grid();
}
}
export = Game;
网格.ts:
import Game = require('Game');
class Grid
{
public SeeIfStaticWorks()
{
console.log(Game.Game);
if (Game.Game)
alert('Instance is defined!');
else
alert('Instance is undefined!');
}
}
export = Grid;