2017-06-12 24 views
0

所以我有这个方法的模式:我对实例方法有什么误解?

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未定义。实际上,在comparePassword方法中,this未定义。我的理解是,this将引用调用方法的对象,在这种情况下,user[0]

那么引用调用它自己的实例方法的对象的正确方法是什么?

回答

1

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/

相关问题