10

In this thread I found a JavaScript code snippet which I want to use.

The code looks like:

(function(global) {
  // the function code comes here
})(this);

How can i call this function to execute the code? What do I have to pass in for this global variable?

Community
  • 1
  • 1
BetaRide
  • 14,756
  • 26
  • 84
  • 153
  • 1
    You don't have to pass in anything - `this` (whatever `this` is - that would depend on the context) is already being passed as the value of the `global` parameter. – Anthony Grist Apr 25 '12 at 11:46

3 Answers3

19

The function is immediately executed, you do not execute it by calling it.

It is a function literal definition, followed by two parens which causes that function to invoke immediately. Read more: Immediately-Invoked Function Expression (IIFE)

Whatever code you place inside is run right away. Anything placed in the invocation parens is passed into the function as an argument. Assuming your sample code was defined in the global scope, this is the window object, and is referenced as global within the function body. It is a great way to encapsulate your programs to avoid variable collision, force strict mode, and much more.

JAAulde
  • 18,107
  • 5
  • 49
  • 59
16

This construct defines a function:

function(global) {
  // the function code comes here
}

and immediately calls it, passing this as a parameter:

([function])(this)

The identifier global is simply the name of this parameter inside the function body. For example, try

console.log(this); // outputs something
(function(global) {
    console.log(global); // outputs the same thing as above
})(this);
Jon
  • 396,160
  • 71
  • 697
  • 768
1

How can i call this function to execute the code?

It is already being called: (this)

What do I have to pass in for this global variable?

this

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205