简体   繁体   中英

Typescript - Invoking subclass's instance method from base class

I'm building a project (small game) and i'm trying to find solution for my issue.

I have code where i use base class Entity which has necressary methods for subclasses (objects) like movement, model rendering etc... Functions which are used in all other subclasses Fe

  • Entity -> Base Class,

    • SpellObject -> Subclass / Extends Entity

    • PlayerObject -> Subclass /extends Entity

    • UnitObject -> Subclass / Extends entity

In entity i have default movement method where i check collision but when the collision is hitted, i want to invoke subclass method onCollisionHit which is defined in XXXObject (For every object i need separated code)

My Code

Entity:


class Entity
{
    constructor(obj: EntityInterface)
    {
        ///
    }

    public doMove(...):void
    {
        // SpeedX SpeedY...
        // ...
        if (collisionHit)
            // getSubclass f.e PlayerObject.onCollisionHit()

        this.addPosition(speedX, speedY)
        //...
    }

    // ....

SpellObject/PlayerObject/...


export class xxxObject extends Entity
{
    constructor(obj:XXXInterface)
    {
        // ...
    }

    public onCollisionHit(...):void
    {
        // Do something (for SpellObject ->Call spell Disapear, for Player set MovementX/Y to 0..
    }

How can i invoke onCollisionHit from base class in this example? One possible solution i found is to link subclass instance to variable of base class

  • in Entity -> protected subclass;

  • in xxxObject -> this.subclass = this; -> in doMove() -> when collision hit call -> if (this.subclass) this.subclass.onCollisionHit()

Im not sure if it is only a solution by wasting memory.. Thanks all for response.

Make onCollisionHit an abstract method of Entity , and make Entity itself abstract, since you seem to expect every Entity subclass to implement the method and presumably you should never be able to instantiate just a raw Entity.

abstract class Entity
{
    constructor(obj: EntityInterface)
    {
        ///
    }

    public doMove(...):void
    {
        // SpeedX SpeedY...
        // ...
        if (collisionHit)
            this.onCollisionHit();

        this.addPosition(speedX, speedY)
        //...
    }

    public abstract onCollisionHit():void;
    // ....

Then you can use eg this.onCollisionHit() from within Entity method implementations. If you have need to instantiate Entity instead of a subclass, you can ditch the abstract idea and just have a default (empty?) implementation of onCollisionHit() and have subclasses override it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM