Reputation: 77
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();
}
The first code logs id where as the second code gives error. I understand that getUserDetails has no access to id but how come the callback passed to getUserDetails has access to id?
Upvotes: 1
Views: 48
Reputation: 1086
id
is a variable scoped to the callback function of socket.on('data')
event.
the getUserDetails
method is not in that scope - therefore it can't access this variable.
The function you sent as a parameter to getUserDetails
is declared inside the scope of the callback function where the id
variable is in, so it can access it.
Upvotes: 1