【问题标题】:this is undefined in typescript class这是在打字稿类中未定义的
【发布时间】:2021-08-30 22:00:12
【问题描述】:

我试图理解为什么“this”有时可能在类中未定义,以及如何解决它:

import { UserDatabase } from './user.database';

export class UserService {
    private userDatabase = new UserDatabase();
    
    
    async login (request: Request, response: Response) {
        let {email, password} = request.body;
        
        const user = await this.userDatabase.login(email, password);
...

错误日志:

(node:3254) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'userDatabase' of undefined

【问题讨论】:

    标签: node.js typescript this


    【解决方案1】:

    this 的常见问题。

    您可以将方法绑定到类上下文:

    export class UserService {
      constructor () {
        this.login = this.login.bind(this);
      }
    
      ...
    
    }
    

    在此处阅读更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 2016-11-06
      相关资源
      最近更新 更多