打字稿:调用公共函数

时间:2017-07-04 07:56:11

标签: node.js express typescript

我是typescript的新人。在我的node-express应用中,我想调用公共功能。但是this总是undefined,所以当我调用公共函数时,它总是会抛出错误。我的代码如下:

app.ts

 import * as express from 'express';
 import User from './user/ctrl';
 class App {
    public express: express.Application;
    constructor() {
       this.express = express();
       this.routes();
    }
    private routes():void {
       let router = express.Router();
       router.get('/', User.index);
       this.express.use('/', router);
    }
 }

export default new App().express;

./用户/ ctrl.ts

class User {
   public demo:string;
   constructor() {
      this.demo = "this is text";
   }

   public infox() {
       console.log("demoo test : ", this.demo);
   }

   public index(req:any, res:any) {
       console.log(this) // output: undefined
       this.infox(); // throw an error.
   }
}

const user = new User();
export default user; 

服务器在端口3000运行。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

当您传递User.index函数的引用时,其中的this将根据其调用方式而更改。或者当严格模式开启时this将是未定义的。

router.get('/', User.index);更改为router.get('/', (req, res) => User.index(req, res));。请注意,User.index包含在箭头函数中,该函数在调用this时捕获正确的User.index

请参阅red flags for this in TypeScript