-1
我是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;
./user/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;
Server运行在端口3000
。
任何建议?
阅读JavaScript中的this范围。 – mingos
'User.index'是**不是**的静态函数,所以你不能像这样传递它。如果它是一个静态函数,那么你不能在其中使用'this'。下定决心。 –
在后台使用TS是否值得?对我来说似乎很奇怪... – Lazyexpert