31

I see a piece of JavaScript code in my Node.js application.

( function() { console.log("gg") } )(this)

I would like to know why use => ( function(){} )(this) this type of structure, and how does this compile.

I am understanding why we have this two brackets ()(), and why this code would work.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Terry Chen
  • 427
  • 6
  • 9

1 Answers1

22

This is a self invoking anonymous function. This pattern is useful when you want to hide variables from the global namespace.

(function(){
    var foo = "foo";
})();

console.log(window.foo); // undefined

Also see What do parentheses surrounding a JavaScript object/function/class declaration mean?

What advantages does using (function(window, document, undefined) { … })(window, document) confer?

Community
  • 1
  • 1
webpapaya
  • 809
  • 12
  • 21
  • 1
    How about (function(){})(this); Does "this" invoke this function? How about (function(global, requirejs, require){})(this, requirejs, require) ? – Terry Chen Mar 11 '14 at 19:20
  • 1
    these are just additional parameters which you can pass to the given function I'll fix this in my answer – webpapaya Mar 11 '14 at 20:02
  • i think this explains everything you need to know [link](http://stackoverflow.com/questions/5020479/what-advantages-does-using-functionwindow-document-undefined-windo) – webpapaya Mar 11 '14 at 20:12