I got a simple twitter bootstrap
message frame that I’m write on, with some little jQuery effects.
First I fade out the board, and once it completed fading out, I’m writing what I want to and them fade it in again.
I got 2 versions:
the first, using a local defined function:
function postMessage(message, context) {
if(typeof context === 'undefined')
context = "info";
var newClass = "alert alert-" + context;
var messageBoard = $("#messageBoard");
// Fade out
messageBoard.fadeOut('slow', postFadeOut);
var postFadeOut = function() {
alert("XX");
// $(this).attr('class', newClass);
// $(this).html(message);
// // Fade in again
// $(this).fadeIn('slow');
}
}
It won’t trigger the alert("XX")
, yet:
function postMessage(message, context) {
if(typeof context === 'undefined')
context = "info";
var newClass = "alert alert-" + context;
var messageBoard = $("#messageBoard");
// Fade out
messageBoard.fadeOut('slow', postFadeOut);
}
function postFadeOut() {
alert("XX");
// $(this).attr('class', newClass);
// $(this).html(message);
// // Fade in again
// $(this).fadeIn('slow');
}
Will trigger. Why?
2
Answers
Try declaring
postFadeOut
variable before call tomessageBoard.fadeOut('slow', postFadeOut)
This is a variable hoisting effect.
In JavaScript, variables are hoisted. That means that in the scope they are declared, they’re available in any line of code, even if declared after that line. However, their value, or initialization, happens in the order the code is written. For example:
As you can see,
a
is available in the first alert (no exception is thrown), but it’s uninitialized.The code above is for all purposes identical to:
In your 1st example, the
postFadeOut
variable is hoisted like that, yet in the.fadeOut
call it’s uninitialized and it’s value isundefined
.The 2nd version works since functions are available within the scope they’re declared regardless of order of code. That’s due to the fact that the engine first parses the entire code, “remembering” the functions in that pass, and only then starts executing from the first line forward.