1

While looking at the code of uuid.js I have noticed this pattern for the definition of the whole api.

(function() {/*...*/}).call(this);

What are the advantages of such a pattern in javascript ?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169

2 Answers2

4

It's just an immediately invoked function expression that has a defined context (this). A normal IIFE will have the global object as its context.

Reading the source file you linked to, in this context (no pun intended) they're using this to obtain an explicit reference to the global object, without assuming that it's named either window (for a browser) or global (for node.js, etc).

(An IIFE is a common construct to create a new scope in which variables may be declared without polluting the global name space, and having the code within the block executed immediately).

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

The main advantage of doing so is that you can declare as many variables as you need inside the function, and they wouldn't pollute the global scope.

See also: module pattern.

Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80