开发者

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://jsfi开发者_开发技巧ddle.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. E.g.

  "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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜