简体   繁体   中英

Scoping in typescript

I created a sample app in nodeJs that uses pg-promise to execute a query in Postgres. And wrapped it with a class called PostgresDataAccess. On the code below, why can't I access the "dal" object from my get and getOne function. The "this" keyword returns undefined. Can someone please explain 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;

why can't I access the "dal" object from my get and getOne function. The "this" keyword returns undefined

Change :

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

to

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

As arrow functions preserve this

Same for getOne .

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