Thursday 26 September 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...