Is there any advantage of wrapping a function with an anonymous function?
I mean a particular example:
function asyncFuntion(callback) {
setTimeout(callback, 6000);
};
asyncFuntion(function() {
console.log('Calling after 6 s.');
});
and with the wrapped function:
function asyncFuntion(callback) {
setTimeout(function() {
callback();
}, 6000);
};
asyncFuntion(function() {
console.log('Calling after 6 s.');
});
In both cases output is the same. So is there any difference?
The second version is what I found learning js.
I realize that such a form is useful when we need closures but here?
The second form allows you to pass arguments to
callback, whereas the first form doesn’t.If you’re not passing arguments, then there is no advantage in wrapping the function whatsoever.
To be more thorough,
Function.prototype.bindcan help us with the first form:However, you will need to provide this method to browsers that don’t support the event (namely Opera, Safari and IE 8, 7, 6). The code to shim the method is available on the MDN documentation page.