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?
-
I would suggest reading, benalman.com/news/2010/11/…Anthony Forloney– Anthony Forloney2013年08月09日 20:06:17 +00:00Commented Aug 9, 2013 at 20:06
-
1See also: How does an anonymous function in JavaScript work?.George Cummins– George Cummins2013年08月09日 20:07:34 +00:00Commented Aug 9, 2013 at 20:07
-
@KevinDeVoe your duplicate is betterDave– Dave2013年08月09日 20:07:39 +00:00Commented Aug 9, 2013 at 20:07
4 Answers 4
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.
Comments
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 :)
Comments
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
Comments
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