我对实例方法有什么误解?
What do I misunderstand about instance methods?
所以我有一个使用这种方法的架构:
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
我能够验证 user[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/
所以我有一个使用这种方法的架构:
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
我能够验证 user[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/