简体   繁体   中英

jQuery: Rewriting Anonymous Callback to a Named Function

If I do this:

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

h1 will slide up, then the first div will fade out.

However, if I do this:

function last() { $('div:first').fadeOut(); }

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

h1 will slide up and div will fade out at the same time!

How can I make my second example work the same as the first one, where fadeOut() is called AFTER slideUp()?

You don't need to use the function return value (which you get by calling the function), but the function body:

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

What you did is the same as this:

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

So you were just executing the last function inline, and then passing the return value (which is undefined since it returns nothing) as a parameter to the slideUp 's callback function.


Hope this example will help you understand:

 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM