1

Trying to figure out what this means in javascript.

(function(document) { ... } )(document);

It is isn't using jQuery, so is this just a javascript way of making this wait till document is ready to execute? Thanks.

hunterc
  • 1,957
  • 2
  • 15
  • 18
  • A general pattern is to use immediately invoked function expressions `(function () { /* code here */ }());` to create nested scopes (variable environments). So, if you have a block of code within a whole lot of other code, and that block needs a bunch of variables, it makes sense to use that pattern to prevent those variables from polluting the outer code. – Šime Vidas Sep 06 '13 at 14:47

4 Answers4

4

This won't wait for the document to be ready, this will execute the content of the function immediately. Putting the function definition in parenthesis makes it an expression, which returns a value being the function, making it directly executable. This pattern is called an Immediately-Invoked Function Expression (IIFE).

This is probably used in conjunction with a minifier like the Closure Compiler.

Inside the function, document is a local variable. This makes it possible for the minifier to reduce its name to a one or two character name.

Note also that all variables defined inside the function will be local : they won't leak in the global scope, which may be interesting if this is only part of the script.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

This creates an anonymous function that takes a single argument, and immediately calls it passing document as the argument.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

This:

function(document) { ... } 

creates a function taking one paremeter.

This:

(function(document) { ... })

makes it (the code, not the function) a valid expression. See here.

This:

(function(document) { ... } )(document);

calls that function with document as a parameter.

It's a basic modularization pattern. In different environments you could've passed some other object instead of document, but nothing inside that function has to know bout it.

Community
  • 1
  • 1
soulcheck
  • 36,297
  • 6
  • 91
  • 90
1

This is called self-executed function. It evaluates the anonymous function taking a parameter called document with that parameter passed in.

zs2020
  • 53,766
  • 29
  • 154
  • 219