Node.jscallback函数

我是Node.js平台的新手,我尽可能地学习。 玩过callback之后,有一件事让我很困惑:

所以,我有这个function:

function registerUser(body, res, UserModel){ var userJSON = { email : body.email, password : body.password, accessToken : null }; var user = null; var userAlreadyExists = false; UserModel.find({}).select('email').exec(function(err, results){ if(err){ console.log('Database error : ' + err); // send the appropriate response }else{ for(var index in results){ if(results[index].email == userJSON.email){ userAlreadyExists = true; break; } } if(userAlreadyExists){ // send the appropriate response }else{ newAccessToken(UserModel, function(error, token){ if(error != null){ // handle the error }else{ userJSON.accessToken = token; user = new UserModel(userJSON); user.save(function(err){ if(err){ // .. handle the error }else{ // .. handle the registration } });}});}}});} 

然后接受callback函数:

 function newAccessToken(UserModel, callback){ UserModel.find({}).select('email accessToken').exec(function(err, results){ if(err){ callback(err, null); }else{ // .... bunch of logic for generating the token callback(null, token); } }); } 

我期望callback不起作用(可能会抛出一个错误),因为userJSONuserJSON都没有在它的上下文中定义( userJSON ,这不完全正确,但是因为它执行asynchronous – 一段时间后 – ,我期望callback失去了对那些在registerUser函数中本地定义的variables的引用)。 相反,这个例子完美地工作,callback函数保持它与在registerUser函数中定义的那两个variables的引用。 有人可以解释我是如何asynchronouscallback和参考工作,为什么这个例子的工作?

H i,你调用的函数你想访问的variables的范围内,所以所有的访问都是好的。

这不是一个nodejs的东西,普通的JS以同样的方式工作。

区别

1)将无法访问一个名为'foo'的变种

 function finishfunction() { console.log(foo); /* undefined */ } function functionwithcallback(callback) { callback(); } function doStuff() { var foo = "bar"; functionwithcallback(finishfunction); } doStuff(); 

2)像你一样,访问'foo'是好的。

  function functionwithcallback(callback) { callback(); } function doStuff() { var foo = "bar"; functionwithcallback(function() { console.log(foo) /* all fine */ }); } doStuff(); 

这些被称为闭包,而在JavaScript中,范围处理是特殊的。 检查这个文件:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures