【发布时间】:2012-10-13 14:33:17
【问题描述】:
我正在尝试在以下函数中重复使用名为 user 的变量:
UserModel.prototype.authenticate = function (doc, callback) {
// check to see if the username exists
this.users.findOne({ username: doc.username }, function (err, user) {
if (err || !user)
return callback(new Error('username not found'));
// hash the given password using salt from database
crypto.pbkdf2(doc.password, user.salt, 1, 32, function (err, derivedKey) {
if (err || user.password != derivedKey)
return callback(new Error('password mismatch'));
// explicitly define the user object
var user = {
_id: user._id,
type: user.type,
username: user.username,
displayname: user.displayname
};
return callback(err, user);
});
});
};
我尝试在pbkdf2 回调函数中重新定义user 变量。这不像我预期的那样工作。我比较user.password != derivedKey 的行会中断,因为user 在运行时在此处未定义。 user 不应该仍然是来自findOne 回调方法参数的实例吗?如果我将两个 user 变量中的任何一个更改为其他名称,它就会起作用。
我可以重命名变量,但这仍然让我感到疑惑。
【问题讨论】:
标签: javascript node.js scope