Saturday, February 23, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...