1

I saw many js minified files having the structure:

(function($,window) ...... )(jQuery,this);

what is with this structure? It's like divided into 2 pairs of parantheses, the very big first one, and the (jQuery,this); in the end.

Sergiu Todirascu
  • 1,367
  • 15
  • 23

3 Answers3

3

It's called an immediately executed function, and is used in this case as a closure to encase all code within a scope, rather than polluting the global environment.

Like any function, an immediately executed one can receive arguments. So it is here; the first argument is the global jQuery object, while the second one is the outer context, window.

See immediately-invoked function expression.

Sergiu Todirascu
  • 1,367
  • 15
  • 23
Mitya
  • 33,629
  • 9
  • 60
  • 107
0

It's an immediately-invoked function expression. Very common in JavaScript.

user229044
  • 232,980
  • 40
  • 330
  • 338
0

(function($,window) ...... )(jQuery,this);

The whole thing is IIFE which sends jQuery object to be used as a dollar sign inside the IIFE

The other parameter is (in browser environment) the window object which is this (in global scope).

The main goal is to use $ and window inside the function without the fear that something was overwritten.

It is all done in the IIFE which creates its own scope which is not polluting the global scope.

Also

There is another trick to send nothing as an undefined parameter

user229044
  • 232,980
  • 40
  • 330
  • 338
Royi Namir
  • 144,742
  • 138
  • 468
  • 792