【发布时间】: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