32

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.

1
  • 2
    Ok, the interesting thing is though, why (this) is passed?!?CommentedMar 7, 2014 at 18:35

1 Answer 1

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?

3
  • 1
    How about (function(){})(this); Does "this" invoke this function? How about (function(global, requirejs, require){})(this, requirejs, require) ?CommentedMar 11, 2014 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
    CommentedMar 11, 2014 at 20:02
  • i think this explains everything you need to know link
    – webpapaya
    CommentedMar 11, 2014 at 20:12

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.