【问题标题】:Why can't I re-use a variable name inside of a callback?为什么我不能在回调中重用变量名?
【发布时间】: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


    【解决方案1】:

    答案是因为hoisting,即使你在其他表达式(user.password != derivedKey)中使用变量usersvar users)之后,它也会被首先解析,留下原来的@987654327 @引用被覆盖。 在hoisting 上有several docs,最好在他们那里达到顶峰。

    【讨论】:

    • 感谢您的链接。这是了解 Javascript 的一个重要事实。很高兴我现在知道了! :)
    【解决方案2】:

    问题是,您在函数上下文中声明了一个名为 user 的变量:

    var user = { };
    

    这将覆盖/重叠由外部函数上下文声明为形式参数的user。在您的 if 语句 之后声明该变量并没有帮助。 var函数声明 声明的变量在解析时被提升,所以事实上,var user 语句被放置在你的内部函数之上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      相关资源
      最近更新 更多