Typescript Express中间件

我有一个简单的authentication中间件的快递。 它检查标题,如果所有的酷它调用next()

现在,当我在“DoSomething”中,“this”等于全局,而不是“Test”的实例,并且“this.DoSomeThingPrivate”未定义。

我试过了

DoSomeThingPrivate :() => void; this.DoSomeThingPrivate = () => { ... } 

模式。 但也是行不通的。

 import express = require('express'); var app = express(); class Test { constructor() { } DoSomething(req:express.Request, res:express.Response, next:Function) :void { this.DoSomeThingPrivate(); } private DoSomeThingPrivate() :void { } } var test = new Test(); app.use(test.DoSomething); 

有关这个

有任何想法吗…

谢谢

你已经传递了一个参考,只是函数本身。 该函数的实例将是全局的。 您需要将函数绑定到test实例。

 app.use(test.DoSomething.bind(test)); 

以下应该工作正常,即使用胖箭头DoSomethingDoSomethingPrivate

 import express = require('express'); var app = express(); class Test { constructor() { } // important: DoSomething = (req:express.Request, res:express.Response, next:Function) => { this.DoSomeThingPrivate(); } private DoSomeThingPrivate() :void { } } var test = new Test(); app.use(test.DoSomething); 

注意:您不应该需要使用bind 。 另外https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1