Rya*_*yan 2 javascript scope node.js
我正在尝试重用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);
});
});
};
Run Code Online (Sandbox Code Playgroud)
我尝试重新定义回调函数user内部的变量pbkdf2.这不像我期望的那样有效.我比较的行user.password != derivedKey断开,因为user在运行时这里未定义.不应该user仍然是findOne回调方法参数的实例?如果我将两个user变量中的任何一个更改为其他变量,它就会起作用.
我可以重命名变量,但这仍然让我感到疑惑.
问题是,你声明了一个user在函数上下文中调用的变量:
var user = { };
Run Code Online (Sandbox Code Playgroud)
这将覆盖/重叠user由外部函数上下文声明为形式参数的内容.在if语句之后声明该变量没有帮助.由声明var和函数声明声明的变量在分析时被提升,因此实际上,该var user语句放在内部函数的顶部.
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |