Reputation: 1573
Is there any advantage of wrapping a function definition in an immediate anonymous function?
Here is an example from the jsfeat library:
var get_channel = (function () {
return function(type) {
return (type & 0xFF);
}
})();
Or is it better to just do the following?
var get_channel = function(type) {
return (type & 0xFF);
};
It seems that in this case there are no advantages in favour of the first version:
Upvotes: 2
Views: 118
Reputation: 66324
There are some advantages, but they aren't visible in the example you've provided. The advantages are that you can
For example, you could make a cross-browser XHR function like this
var XHR = (function () {
if (window.XMLHttpRequest)
return function () {
return new XMLHttpRequest();
};
else
return function () {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}());
Now future calls of XHR
don't need to work out the if
logic, which would always be the same anyway.
Upvotes: 2