Pin*_*tac 3 node.js express typescript
我有一个简单的auth中间件用于表达.它检查标题,如果所有酷,它调用next()
现在,当我在"DoSomething"中时,"this"等于全局,而不是"Test"和"this.DoSomeThingPrivate"的实例未定义.
我试过了
DoSomeThingPrivate :() => void;
this.DoSomeThingPrivate = () => {
...
}
Run Code Online (Sandbox Code Playgroud)
图案.但也行不通.
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);
Run Code Online (Sandbox Code Playgroud)
有任何想法吗...
谢谢
以下应该工作正常,但DoSomething不使用胖箭头DoSomethingPrivate:
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);
Run Code Online (Sandbox Code Playgroud)
注意:您不应该使用bind.另请https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1
您已经将参考传递给函数本身.该函数的实例将是全局的.您需要将函数绑定到实例test.
app.use(test.DoSomething.bind(test));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9674 次 |
| 最近记录: |