TypeScript Access Static Variables Using Instances

后端 未结 1 1910
北海茫月
北海茫月 2021-02-15 08:58

So in most OOP languages static variables can also be called class variables, ie their value is shared among all instances of this class. For example,

相关标签:
1条回答
  • 2021-02-15 09:30

    First option is to create instance accessors to static variable:

    class GreenBullet
    {
       static ammo: number = 0;
       get ammo(): number { return GreenBullet.ammo; }
       set ammo(val: number) { GreenBullet.ammo = val; }
    }
    var b1 = new GreenBullet();
    b1.ammo = 50;
    var b2 = new GreenBullet();
    console.log(b2.ammo); // 50
    

    If you want all subclasses of Bullet (including itself) to have separate ammo count, you can make it that way:

    class Bullet
    {
       static ammo: number = 0;
       get ammo(): number { return this.constructor["ammo"]; }
       set ammo(val: number) { this.constructor["ammo"] = val; }
    }
    class GreenBullet extends Bullet { }
    class PinkBullet extends Bullet { }
    
    var b1 = new GreenBullet();
    b1.ammo = 50;
    var b2 = new GreenBullet();
    console.log(b2.ammo); // 50
    var b3 = new PinkBullet();
    console.log(b3.ammo); // 0
    

    On a side note, I'm fairly sure you should not store bullet count in a static variable.

    0 讨论(0)
提交回复
热议问题