2017-07-04 70 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