This is best explained by a code example, so can anyone explain why (in technical terms) the anonymous function passed to test doesn’t get called after the jQuery hide event?
UPDATE: Not that is really matters for this example what this is referring to, but for clarity lets say test function is in the global scope and this is an anchor element.
test(this, function() {
alert('Called by anonymous function!');
});
function test(object, callback) {
$(object).hide('slow', callback);
}
Changing:
$(object).hide('slow', callback);
To:
$(object).hide('slow', callback());
works. Is this because callback isn’t a named function in the current context or global window object?
This is the correct way to do it.
http://jsfiddle.net/6dFm6/6/
Calling remove after the hide animation will remove the object and result in the animation callback not being called.
The reason it works in jsfiddle.net/6dFm6/1 is because the callback is executed at runtime and the value is passed and called during the callback event.
See these articles for varying level of clarity on what is returned by ‘functionName()’ as the callback. It appears ‘undefined’ is returned by the call, however the execution still happens at the correct time.
When to use () after a callback function name?
In JavaScript, does it make a difference if I call a function with parentheses?
Callback function – use of parentheses
do I need parenthesis when using a named function as an jquery ajax success callback
javascript syntax: function calls and using parenthesis