-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