TypeScript 0.9.1.1 を使用して、別のモジュール/ファイルから静的変数にアクセスしようとすると、未定義になります。
コード例:
アプリケーション:
import Game = require('Game');
var game = new Game();
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;
Grid.ts:
import Game = require('Game');
class Grid
{
public SeeIfStaticWorks()
{
var shouldNotBeUndefined = Game.Game;
}
}
export = Grid;
Game.Game
呼び出す前に調べるthis.Grid.SeeIfStaticWorks();
と、次のように定義されていることがわかります。
しかし、内部からアクセスしようとすると、SeeIfStaticWorks()
未定義です:
質問: 他のモジュールから静的変数にアクセスするにはどうすればよいですか?
アップデート:
1 つのファイルからすべてのコードを実行すると、モジュール間で static 変数を使用できます ( demo here )。
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()
。
アプリケーション:
import Game = require('Game');
var game = Game.Game;
game.Grid.SeeIfStaticWorks();
Game.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;
Grid.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;