Используя TypeScript 0.9.1.1, при попытке доступа к статической переменной из другого модуля/файла она не определена.
Пример кода:
App.ts:
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()
он не определен:
Вопрос: как получить доступ к статическим переменным из других модулей?
Обновление:
Запуск всего кода из одного файла позволяет использовать статическую переменную в модулях (demo здесь):
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()
:
App.ts:
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;