使用实例的TypeScript访问静态变量

使用实例的TypeScript访问静态变量

本文介绍了使用实例的TypeScript访问静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在大多数OOP语言中,静态变量也可以称为 class 变量,即,其值在该类的所有实例之间都是 shared .例如,在我的游戏中,我有一个Bullet类,该类由GreenBulletPinkBullet扩展.我希望这些子类有一个名为ammo的类"或静态"变量,以便我可以跟踪该特定弹药类型的弹药计数.但是这里有个问题:我希望能够通过子类的实例访问此属性.

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, in my game I have a class Bullet which is extended by GreenBullet and PinkBullet. I want these subclasses to have a "class" or "static" variable called ammo so 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.

示例:

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

我希望所有GreenBullet实例都知道其弹药计数的变化.

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

推荐答案

第一个选择是创建静态变量的实例访问器:

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

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

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.

这篇关于使用实例的TypeScript访问静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:37