Explain the following javascript statement? -


this question has answer here:

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

i've been learning javascript while now. why function declaration above encapsulated in '('s , why there '();' in end?

i can imagine constructor function, because of '();' in end. why object wrapped in simple brackets?

this code equivalent to:

function ninja() {     // nothing here }  var ninja = new ninja(); 

though in code listed, function/object ninja not global scope.

the code (function() {...})(); says "take whatever function contained inside here , execute immediately". it's creating anonymous function , calling right afterwards.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -