我目前正在处理一个作为express中间件的类。在进入类之前,请记住,稍后我将通过首先创建类“身份验证器”的实例,然后将其方法注入到
app.use(authInst.express)所以关键是这个函数的执行上下文(这个)。这就是我到目前为止掌握的代码
备选方案1
class Authenticator {
opts:IAuthOpts ;
express: RequestHandler| ErrorRequestHandler
constructor(opts:IAuthOpts){
this.opts = opts;
this.express = function(req:Request, res:Response, next:NextFunction){
if(this.opts.enabled) {
mainController(req, res, next, this.opts)
} else {
next();
}
}
}
}这很管用。然而,我不想在构造函数中编写函数,因为我发现它的代码很难看。将express方法直接放在类中,如下所示
不工作
class Authenticator {
opts:IAuthOpts;
constructor(opts:IAuthOpts){
this.opts = opts;
}
express(req, res, next){
if(this.opts.enabled) {
mainController(req, res, next, this.opts)
} else {
next();
}
}
}不会工作,因为来自express的执行上下文将给我以未定义的方式。所以剩下的就是用这种方法
备选方案2
class Authenticator {
opts:IAuthOpts ;
express: RequestHandler| ErrorRequestHandler
constructor(opts:IAuthOpts){
this.opts = opts;
this.express = _express.bind(this);
}
private _express(req, res, next){
if(this.opts.enabled) {
mainController(req, res, next, this.opts)
} else {
next();
}
}
}到目前为止,这也是我最喜欢的解决这个问题的解决方案,因为将方法外包给另一个文件和保持文件小也很容易。不利之处在于束缚。我不太喜欢bind,因为我希望我的函数返回相同的值,如果我用相同的参数调用它们,不管它们是从哪里调用的,在这种情况下,您总是需要将类绑定到它。
是否有更好的解决方案可以将方法外包给TypeScript类,而不需要将执行上下文注入绑定?
发布于 2018-10-23 03:05:11
可以使用箭头函数代替绑定:
class Authenticator {
opts:IAuthOpts ;
constructor(opts:IAuthOpts){
this.opts = opts;
}
express = (req, res, next) => {
if(this.opts.enabled) {
mainController(req, res, next, this.opts)
} else {
next();
}
}
}如果您想要将实现移动到另一个文件,最好定义一个函数,该函数将Authenticator与req、res和next一起作为普通参数,然后从箭头函数调用该函数:
class Authenticator {
opts:IAuthOpts ;
constructor(opts:IAuthOpts){
this.opts = opts;
}
express = (req, res, next) => otherFunction(this, req, res, next);
}
// In other file
function otherFunction(authenticator: Authenticator, req: Request, res: Response, next: NextFunction) {
if(authenticator.opts.enabled) {
mainController(req, res, next, authenticator.opts)
} else {
next();
}
}如果这不是你要找的,请澄清这个问题。
https://stackoverflow.com/questions/52932380
复制相似问题