this
在方法中不可用。我的代码(注释块)中有关可用内容的更多细节,很难用纯文本来解释。这可能是重复的,但我在任何地方都找不到直接答案。
此代码有问题,还是有逻辑解决方法?
class CheckParameters {
get parameters() {
return this._parameters;
}
constructor(parameters) {
this._parameters = parameters;
console.log(this); //this is defined
}
CheckQueryParam (req, res, next) {
console.log(this); // undefined
let parameterChecks = this._parameters.map(param => { // TypeError: Cannot read property '_parameters' of undefined
return new Promise((resolve, reject) => {...});
});
Promise.all(parameterChecks)
.then(() => next())
.catch((error) => {
console.error(error);
res.status(400).send(error)
});
}
}
console.log(LimitAndOffset.parameters); //Also this is defined
const LimitAndOffset = new CheckParameters([
new Parameter( //Parameter is another class, this works perfectly
"limit",
Number,
[Validators.Number],
true
),
new Parameter(
"offset",
Number,
[Validators.Number],
true
)
]);
app.get('/', LimitAndOffset.CheckQueryParam, function (req, res) {
res.status(200).json('piemel');
});