【问题标题】:Scoping in typescript打字稿中的范围
【发布时间】:2018-01-29 04:43:00
【问题描述】:

我在 nodeJs 中创建了一个示例应用程序,它使用 pg-promise 在 Postgres 中执行查询。并用一个名为 PostgresDataAccess 的类包装它。在下面的代码中,为什么我不能从我的 get 和 getOne 函数访问“dal”对象。 “this”关键字返回未定义。有人可以解释一下吗?

import { Router, Request, Response, NextFunction } from 'express';
import { PostgresDataAccess } from '../dal/postgres';

const config = require('../../config/config');

export class ProjectRouter {
  public router: Router;

  dal: PostgresDataAccess;

  /**
   * Construct the Project Router.
   */
  constructor() {
    this.dal = new PostgresDataAccess(config);
    this.router = Router();
    this.init();
  }

  /**
   * Take each handler, and attach to one of the Express.Router's endpoints.
   */
  init() {
    this.router.get('/', this.get);
    this.router.get('/:id', this.getOne);
  }

  /**
   * GET: Returns all projects.
   */
  get(req: Request, res: Response, next: NextFunction) {
    let projects = this.dal.queryDb('select * from projects', null, res);
  }

  /**
   * GET: Retuns one project by id.
   */
  getOne(req: Request, res: Response, next: NextFunction) {
    let projects = this.dal.queryDb('select * from projects where id = $1', [req.params.id], res);
  }
}

const projectRouter = new ProjectRouter();
export default projectRouter.router;

【问题讨论】:

    标签: node.js typescript scope


    【解决方案1】:

    为什么我不能从我的 get 和 getOne 函数中访问“dal”对象。 "this" 关键字返回 undefined

    改变:

    get(req: Request, res: Response, next: NextFunction) {
      let projects = this.dal.queryDb('select * from projects', null, res);
    }
    

    get = (req: Request, res: Response, next: NextFunction) => {
      let projects = this.dal.queryDb('select * from projects', null, res);
    }
    

    作为arrow functions preserve this

    getOne 也一样。

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2023-03-04
      相关资源
      最近更新 更多