jQuery:重写命名函数的匿名回调



如果我这样做:

$('h1').slideUp('slow', function() { $('div:first').fadeOut(); });

H1 将向上滑动,然后第一个div 将淡出。

但是,如果我这样做:

function last() { $('div:first').fadeOut(); }
$('h1').slideUp('slow', last());

H1 将向上滑动,div 将同时淡出!

如何使我的第二个示例与第一个示例相同,其中 fadeOut() 称为 AFTER slideUp()?

你不需要使用函数返回值(通过调用函数获得),但函数体:

$('h1').slideUp('slow', last);

您所做的与此相同:

var returned = last();             // call to last returns undefined
                                   // so returned has the value undefined
$('h1').slideUp('slow', returned); // simply sending undefined as a callback

所以你只是内联执行last函数,然后将返回值(这很undefined,因为它不返回任何内容)作为参数传递给slideUp的回调函数。


希望这个例子能帮助你理解:

function outer() {
  function inner() {};
  return inner;
}
alert(outer);    // returns the outer function body
alert(outer());  // returns the outer function's return value, which is the inner function

最新更新