var message = 'Spoon!';
$('#foo').bind('click', function() {
alert(message);
});
message = 'Not in the face!';
$('#bar').bind('click', function() {
alert(message);
});
Why are the two output messages are the same: “Not in the face!”;
Isn’t the first message within the closure of ‘foo’ refers to ‘Spoon!’?
Why not?
Please someone explain. I don’t understand the tutorial’s explanation.
That’s because the event handlers are launched asynchronously.
While the message value you’re setting is done in the first thread.
So basically your program will read your whole code, set the value to
'Spoon!', then to the last one you set'Not in the face!'. Then when you click on either buttons it’ll alert the value of message'Not in the face!'.Try putting message in the function, then you’ll see a different message for each. This would work as you expect as you set also the value asynchronously.