Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I see a piece of javascript code in my nodejs application.

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

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

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

share|improve this question

marked as duplicate by VisioN, p.s.w.g, Chris Ballard, James Westgate, mustaccio Mar 27 '14 at 14:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
Ok, the interesting thing is though, why (this) is passed?!? –  DOC ASAREL Mar 7 '14 at 18:35
    
I want to know too –  Terry Chen Mar 11 '14 at 19:35

1 Answer 1

up vote 3 down vote accepted

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?

share|improve this answer
    
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
    
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 –  webpapaya Mar 11 '14 at 20:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.