如何从子类访问主类而不在typescript中传递引用?

时间:2015-11-30 17:51:36

标签: typescript

我正在构建一个打字游戏,其中主要类需要可以从游戏中的任何位置访问。我试图模仿C#/ Unity / Actionscript处理类和实例的方式。

我想避免使用" modules / export"语法,因为我发现它有点违反直觉(为什么即使使用类,如果一切都是模块?),但也许这是我缺乏理解。

game.ts

class Game {
    private score:number = 0;

    constructor() {
        var t = new Tank();
        t.shootGun();
    }

    addScore(i:number){
        this.score += i;
    }
} 

// now we create an instance of our game
var g = new Game();

tank.ts

class Tank {
    constructor() {

    }

    shootGun() {
       // I want to call a function on the 'g' instance created above
       g.addScore("25");
    }
}

我的问题是:坦克(或任何其他在游戏中的某个点运行的实例)如何调用" g"运行main.ts后创建的实例?

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?

class Tank {
    constructor(public g: Game) {

    }

    shootGun() {
        this.g.addScore(25);
    }
}

class Game {
    private score: number = 0;

    constructor() {
        var t = new Tank(this);
        t.shootGun();
    }

    addScore(i: number) {
        this.score += i;
    }
} 

// now we create an instance of our game
var g = new Game();
相关问题