Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration function inside ( ) [duplicate]

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 )?

like image 323
GusDeCooL Avatar asked Feb 18 '23 18:02

GusDeCooL


2 Answers

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);
            }
        }
    };
}());
like image 180
Aaron Kurtzhals Avatar answered Feb 20 '23 08:02

Aaron Kurtzhals


actually, the first line is like this:

(function( window, undefined ) {

})( window );

which is an immediately-invoked function expression.

like image 35
ic3b3rg Avatar answered Feb 20 '23 07:02

ic3b3rg