jQuery callback
function myBeer(param, callback) { alert('Started drinking my beer.\n\nIt has: ' + param); $('#beer').animate({ opacity: 0 }, 5000, function() { // Animation complete. }); if (callback && typeof(callback) === "function") { callback(); } } myBeer('Guiness', function() { alert('Finished drinking my beer.'); });
Using .call and .apply in JavaScript callback
.call takes the value to be used as the this object inside the function as the first parameter, and the remaining arguments to be passed to the function are passed individually (separated by commas of course).
function callback_by_call( arg1, arg2, callback ){ console.log( 'do something' ); var result1 = arg1.replace( 'argument', 'result' ), result2 = arg2.replace( 'argument', 'result' ); this.data = 'some data that can be used for the callback function with `this` key word'; // if callback exists execute it callback && callback.call( this, result1, result2 ); }
.apply takes first parameter is also the value to be used as the this object inside the function, while the last parameter is an array of values (or the arguments object) to pass to the function.
// this is similar to `callback_by_call` // the only difference is we use `apply` instead of `call` // so we need to pass arguments as an array function callback_by_apply( arg1, arg2, callback ){ console.log( 'do something' ); var result1 = arg1.replace( 'argument', 'result' ), result2 = arg2.replace( 'argument', 'result' ); this.data = 'some data that can be used for the callback function with `this` key word'; // if callback exists execute it callback && callback.apply( this, [ result1, result2 ]); }