44
var ninja = (function(){
    function Ninja(){};
    return new Ninja();
})();

Why is the function above encapsulated in parentheses and why is there a (); at the end?

I think it's a constructor function because of the (); at the end, but why is the object wrapped in parentheses?

Sangram Singh
  • 7,161
  • 15
  • 50
  • 79

4 Answers4

15

This code is equivalent to:

function Ninja() {
    // nothing here
}

var ninja = new Ninja();

Though in the code you listed, the function/object Ninja is not global scope.

The code (function() {...})(); basically says "take whatever function is contained inside here and execute it immediately". So it's creating an anonymous function and calling it right afterwards.

7

It's called an Immediately-Invoked Function Expression (or IIFE). It creates a new scope and executes the contents immediately. There are many uses for it; the one I use the most is when the this keyword would change meaning, e.g. in

var someClass = function() {
    this.property = something;
    this.update = (function(obj) {
        function() {
            $('.el').each(function() {
                $(this).html( obj.property );
            });
        };
    )(this);
};

While I want to refer to this.property inside the $('.el').each(), this changes meaning within that scope and refers to the current DOM element that is being looped through with .each(). So by passing this as a parameter into the IIFE (and calling that parameter obj) I can use obj.property to refer to what is this.property when outside the scope of $('.el').each( ..., function() { ... });.

Let me know if that makes sense or if you have any questions :)

asifrc
  • 5,781
  • 2
  • 18
  • 22
1

Why is the function declaration encapsulated in '('s and also why is there a '();' in the end

Its declaring and executing the function at the same time.

You may see: Named function expressions demystified - by Juriy "kangax" Zaytsev

Habib
  • 219,104
  • 29
  • 407
  • 436
0

As suggested: Refering to Benalman

Immediately-Invoked Function Expression (IIFE) Fortunately, the SyntaxError “fix” is simple. The most widely accepted way to tell the parser to expect a function expression is just to wrap in in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

// Either of the following two patterns can be used to immediately invoke
// a function expression, utilizing the function's execution context to
// create "privacy."


(function(){ /* code */ }()); // Crockford recommends this one

(function(){ /* code */ })(); // But this one works just as well
Sangram Singh
  • 7,161
  • 15
  • 50
  • 79