0

Having the following class hierarchy in a Deno Typescript project:

AccountPutController.ts

export class AccountPutController extends HttpController {

    constructor(commandBus: CommandBus) {
        super(commandBus)
    }

    async handle({ params, request, response } : {
            params: { id: string }
            request: any
            response: any
        } 
    ) {
        const { value : requestBody } = await request.body()

        super.dispatch(
            new CreateAccountCommand(
                params.id,
                requestBody.username,
                requestBody.emailAddress,
                requestBody.password
            )
        )
        
        response.status = 201
    }

}

HttpController.ts

export abstract class HttpController {

    private readonly commandBus: CommandBus

    constructor(commandBus: CommandBus) {
        this.commandBus = commandBus
    }

    dispatch(command: Command) {
        if(this === undefined) {
            console.log("This is undefined")
            return
        }            
        this.commandBus.dispatch(command)
    }

}

The condition "this === undefined" evaluates true. Does anybody know why ? How can I prevent that?

AlexTa
  • 5,133
  • 3
  • 29
  • 46

1 Answers1

2

this is determined when you're calling a function. How are you invoking your handle method?

Consider this example:

abstract class Abstract {
  dispatch() {
    console.log(this);
  }
}

class Concrete extends Abstract {
  handle() {
    super.dispatch()
  }
}

If you do this, it works as expected:

new Concrete().handle(); // this === Concrete

If you do that, this will be undefined:

const { handle } = new Concrete();

handle(); // this === undefined
Karol Majewski
  • 23,596
  • 8
  • 44
  • 53