我是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
运行。
有什么建议吗?
答案 0 :(得分:2)
当您传递User.index
函数的引用时,其中的this
将根据其调用方式而更改。或者当严格模式开启时this
将是未定义的。
将router.get('/', User.index);
更改为router.get('/', (req, res) => User.index(req, res));
。请注意,User.index
包含在箭头函数中,该函数在调用this
时捕获正确的User.index
。