Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use (function(global) { ... })(this);

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?

like image 515
BetaRide Avatar asked Apr 25 '12 11:04

BetaRide


2 Answers

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.

like image 104
JAAulde Avatar answered Oct 19 '22 18:10

JAAulde


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);
like image 16
Jon Avatar answered Oct 19 '22 17:10

Jon