2017-07-04 96 views
-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

任何建議?

+0

閱讀JavaScript中的this範圍。 – mingos

+0

'User.index'是**不是**的靜態函數,所以你不能像這樣傳遞它。如果它是一個靜態函數,那麼你不能在其中使用'this'。下定決心。 –

+0

在後臺使用TS是否值得?對我來說似乎很奇怪... – Lazyexpert

回答

2

當您通過參考User.index函數時,它內部的this將根據它的調用方式發生變化。或者當嚴格模式打開時this將不確定。

變化router.get('/', User.index);變爲router.get('/', (req, res) => User.index(req, res));。請注意,當調用User.index時,User.index被封裝在箭頭函數中,該函數捕獲正確的this

請參閱red flags for this in TypeScript