jQuery fadeOut 回调函数 - 为什么局部函数不起作用而全局函数起作用?

jQuery fadeOut callback function - why would local function won't work while global function will?

我得到了一个简单的 twitter bootstrap 消息框,我在上面写了一些 jQuery 效果。

首先我淡出黑板,一旦它完成淡出,我就写下我想要的,然后他们再次淡入。

我有两个版本:

第一个,使用本地定义的函数

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');
    }
}

它不会触发 alert("XX"),但是:

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');
}

触发。为什么?

尝试在调用 messageBoard.fadeOut('slow', postFadeOut)

之前声明 postFadeOut 变量

function postMessage(message, context) {
    if(typeof context === 'undefined') {
        context = "info";
    };
    var newClass = "alert alert-" + context;
    var messageBoard = $("#messageBoard");
    var postFadeOut = function() {
        $(this).attr('class', newClass);
        $(this).html(message);
        // Fade in again
        $(this).fadeIn('slow');
    }
    // Fade out
    messageBoard.fadeOut('slow', postFadeOut);
}

postMessage("message")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="messageBoard">message board</div>

这是 variable hoisting 效果。

在JavaScript中,变量被提升。这意味着在它们被声明的范围内,它们在任何代码行中都可用,即使是在该行之后声明的。但是,它们的值或初始化是按照代码编写的顺序发生的。例如:

alert(a);
var a = 'Some value';
alert(a);

如您所见,a在第一个警报中可用(未抛出异常),但未初始化。

以上代码的所有用途与:

var a;
alert(a);
a = 'Some value';
alert(a);

在您的第一个示例中,postFadeOut 变量是这样提升的,但在 .fadeOut 调用中它是未初始化的,它的值为 undefined

第二个版本有效,因为 函数在它们声明的范围内可用,而不管代码的顺序如何。这是因为引擎首先解析整个代码,"remembering" 该遍中的函数,然后才从第一行开始执行。