Reputation: 455
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.
Example:
var bullet: GreenBullet = new GreenBullet()
if (bullet.ammo <= 0)
return;
bullet.shoot();
bullet.ammo --;
I want ALL instances of GreenBullet
to be aware of this change to their ammo count.
Upvotes: 9
Views: 28882
Reputation: 7004
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.
Upvotes: 18