以下nodejs代码之间的差异
第一个代码
net.createServer(function(socket){ socket.on('data',function(id){ getUserDetails(function(){console.log(id)}); }); }); function getUserDetails(next){ next(); }
第二个代码
net.createServer(function(socket){ socket.on('data',function(id){ getUserDetails(function(){console.log(id)}); }); }); function getUserDetails(next){ console.log(id); next(); }
第一个代码logging第二个代码给出错误的地方。 我明白,getUserDetails有没有访问身份证,但如何传递给getUserDetails有权访问ID的callback?
id
是一个variables作用于socket.on('data')
事件的callback函数。
getUserDetails
方法不在该范围内 – 因此它不能访问这个variables。
您作为getUserDetails
参数发送的函数在id
variables所在的callback函数的作用域内声明,因此可以访问它。