为什么 'this' 在父打字稿 class 中未定义?

Why is 'this' undefined in parent typescript class?

在 Deno Typescript 项目中具有以下 class 层次结构:

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)
    }

}

条件 "this === undefined" 的计算结果为真。有人知道为什么吗?我怎样才能防止这种情况发生?

this 是在调用函数时确定的。您如何调用 handle 方法?

考虑这个例子:

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

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

如果你这样做,它会按预期工作:

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

如果你这样做,this 将是 undefined:

const { handle } = new Concrete();

handle(); // this === undefined