我有一个带有中间件功能的类,我想返回该类。
在中间件中,我想使用this
语句,但是现在它是未定义的。
类:
export class Validator {
constructor(options: validatorOptions) {
this.schema = options.schema
this.validateRequest = options.validateRequest
this.validateResponse = options.validateResponse
}
private validate(req, res, next) {
console.log(this.schema) //undefined
}
public getValidator() {
return this.validate
}
}
类声明:
import {Validator} from './validator/validator'
export const validator = () => {
const config = {
schema,
validateRequest: true,
validateResponse: true
}
let v = new Validator(config)
return v.getValidator()
}
中间件用法:
import { validator } from './middleware'
app.use(validator())
如何在返回的中间件中使用this
?
答案 0 :(得分:1)
validate
是一个回调,应绑定到正确的this
,例如带有班级字段:
private validate = (req, res, next) => { ... }