Could someone please explain what is wrong with this code and how to fix it? I'm truly lost. Thanks!
var messageProcessing = function() {
console.log(message);
};
process.on('message', function(message) {
messageProcessing();
});
Could someone please explain what is wrong with this code and how to fix it? I'm truly lost. Thanks!
var messageProcessing = function() {
console.log(message);
};
process.on('message', function(message) {
messageProcessing();
});
Your messageProcessing()
function tries to reference a message
variable that is out of scope, hence you get a reference error. It can't reference arguments or variables declared inside other functions (unless it is nested inside those other functions, which in this case it isn't, nor would it make sense to nest here).
Note that this isn't really about closures, it is just a basic scope issue.
You can explicitly pass the value through like this:
var messageProcessing = function(message) { // add argument to this function
console.log(message);
};
process.on('message', function(message) {
messageProcessing(message); // pass value through
});
...Or you can avoid the intermediate anonymous function entirely:
var messageProcessing = function(message) { // add argument to this function
console.log(message);
};
process.on('message', messageProcessing); // note no () after messageProcessing
// because this line doesn't invoke it
// it just passes a reference to `.on()`
...Or you can avoid the named function and do everything you need in the anonymous function:
process.on('message', function(message) {
console.log(message);
});
Two other solutions
Pass the message on to the messageProcessing function
var messageProcessing = function(message) {
console.log(message);
};
process.on('message', function(message) {
messageProcessing(message);
});
or, have messageProcessing function inside the function expression that gets the message
process.on('message', function(message) {
var messageProcessing = function() {
console.log(message);
};
messageProcessing();
});