所以我有一个使用此方法的模式:
UserSchema.methods.comparePassword = (candidatePassword) => {
let candidateBuf = Buffer.from(candidatePassword, 'ascii');
if (sodium.crypto_pwhash_str_verify(this.password, candidateBuf)) {
return true;
};
return false;
};
它被称为:
User.find({ username: req.body.username }, function(err, user) {
isValid = user[0].comparePassword(req.body.password);
// more stuff
}
这会导致Error: argument hash must be a buffer
我能够验证用户[0]是否是有效的用户,显然是因为它成功调用了comparePassword
方法,并且失败的是libsodium 函数。
进一步的测试表明,this.password
是不确定的。实际上,this
在comparePassword
方法中是未定义的。我的理解是,this
将引用调用该方法的对象,在本例中为 user[0]
。
那么引用调用它自己的实例方法的对象的正确方法是什么?
this
并不总是像你认为的那样在箭头函数中工作。
胖箭头函数执行词法范围(实质上是查看周围的代码并根据上下文定义this
(。
如果你改回常规的回调函数符号,你可能会得到你想要的结果:
UserSchema.methods.comparePassword = function(candidatePassword) {
let candidateBuf = Buffer.from(candidatePassword, 'ascii');
if (sodium.crypto_pwhash_str_verify(this.password, candidateBuf)) {
return true;
};
return false;
};
有关绑定this
的示例:https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/