Thursday, September 26, 2019

Explain the following JavaScript statement?




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?



Answer



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.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...