Possible Duplicate:
What advantages does using (function(window, document, undefined) { … })(window, document) confer?
Advanced Javascript: Why is this function wrapped in parentheses?
I just checked how jquery is written, then in the first line of it i see this:
(function( window, undefined ) {
});
My question is what is the meaning or reason the declaration of function is inside the (
and )
?
In your example, I see no reason for the parentheses.
For immediately invoked functions, Douglas Crockford recommends and provides a code sample as below. Source is http://javascript.crockford.com/code.html
When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.
var collection = (function () {
var keys = [], values = [];
return {
get: function (key) {
var at = keys.indexOf(key);
if (at >= 0) {
return values[at];
}
},
set: function (key, value) {
var at = keys.indexOf(key);
if (at < 0) {
at = keys.length;
}
keys[at] = key;
values[at] = value;
},
remove: function (key) {
var at = keys.indexOf(key);
if (at >= 0) {
keys.splice(at, 1);
values.splice(at, 1);
}
}
};
}());
actually, the first line is like this:
(function( window, undefined ) {
})( window );
which is an immediately-invoked function expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With