使用TypeScript 0.9.1.1時,當試圖從另一個模塊/文件訪問靜態變量時,它未定義。TypeScript:在RequireJS中使用靜態變量AMD
示例代碼:
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;
調用this.Grid.SeeIfStaticWorks();
前檢查Game.Game
表明,它的定義:
但試圖從訪問它裏面SeeIfStaticWorks()
當它是不確定的:
問題是:如何能夠從其他模塊訪問靜態變量?
更新:
使用跨模塊靜態變量(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()
:
個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;
它不會以這種方式工作,因爲'SeeIfStaticWorks()'會在'Game.Game'實例化之前運行。我發佈了更接近我可能使用的代碼的更新。問題看起來可能與RequireJS有關。尼斯AngularJs/TS視頻順便說一句:) –
因爲它不這樣工作,請你刪除答案?這將有助於更快獲得正確答案。 –
看到我的其他答案 – basarat