TypeScript 使用实例访问静态变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30407697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:40:31  来源:igfitidea点击:

TypeScript Access Static Variables Using Instances

ooptypescript

提问by Nigh7Sh4de

So in most OOP languages static variables can also be called classvariables, ie their value is sharedamong all instances of this class. For example, in my game I have a class Bulletwhich is extended by GreenBulletand PinkBullet. I want these subclasses to have a "class" or "static" variable called ammoso that I can keep track of the ammo count for that specific ammo type. But here is the catch: I want to be able to access this property through an instance of the subclass.

所以在大多数 OOP 语言中,静态变量也可以称为变量,即它们的值在此类的所有实例之间共享。例如,在我的游戏中,我有一个BulletGreenBullet和扩展的类PinkBullet。我希望这些子类有一个名为“类”或“静态”的变量,ammo以便我可以跟踪该特定弹药类型的弹药计数。但这里有一个问题:我希望能够通过子类的实例访问这个属性。

Example:

例子:

var bullet: GreenBullet = new GreenBullet()
if (bullet.ammo <= 0)
    return;
bullet.shoot();
bullet.ammo --;

I want ALL instances of GreenBulletto be aware of this change to their ammo count.

我希望所有实例都GreenBullet意识到他们弹药数量的变化。

回答by zlumer

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:

如果您希望Bullet(包括其自身)的所有子类都具有单独的弹药计数,您可以这样做:

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.

附带说明一下,我很确定您不应该将子弹数存储在静态变量中。