简体   繁体   中英

Understanding JavaScript anonymous vs. named functions in object literals

Why does the "complete" callback for the third animation happen first, before any animations have started?

Script:

$( "#animate" ).delay(2000).animate(
    { "width":    "500px" },
    { "duration": 3000,
      "complete": function(){ $( "#animate" ).append( "1st<br />" ); }}
)
.delay(1000).animate(
    { "width":    "200px" },
    { "duration": 3000,
      "complete": function(){ complete( "2nd" ); }}
)
.delay(1000).animate(
    { "width":    "500px" },
    { "duration": 3000,
      "complete": complete( "3rd" ) }
);

function complete( ordinal ){
    $( "#animate" ).append( ordinal + "<br />" );
};

HTML:

<div id="animate" />

CSS:

#animate
{
    border: 1px solid red;
    height: 200px;
    width:  200px;
}

jsfiddle:

http://jsfiddle.net/nQftS/3/

"complete": complete( "3rd" )

This line will execute the complete function, passing in a parameter of "3rd" and then set the returned value of that function to "complete".

"complete": function(){ complete( "2nd" ); }

This line will instead set "complete" to a function, which, when called, will execute the complete function, passing a parameter of "2nd".

The callback expects a function. You, however, do not pass a function. You call a function.

  "complete": complete( "3rd" )

which appends things as defined within that function. It then returns nothing, so it evaluates to:

  "complete": undefined

Note that passing a function works without parentheses. Eg

  "complete": complete

or

  "complete": function() { ... } // this is also a function

On your last part, wrap it in a function:

.delay(1000).animate( 
    { "width":    "500px" }, 
    { "duration": 3000,
      "complete": function(){complete( "3rd" ) }
    }
);

If you don't do this then the function gets called immediately, which is not what you wanted.

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