javascript - A self invoking anonymous function expression -
(function(){ ... })();
i have looked @ this post , understood bit it. there few more doubts, on how used.
like static block!
since acts static block (self invoking!), can used initializing(like make-believe constants)?
but there no getter
available fetch , use elsewhere!
return, must?
the solution above have return
in function? can fetch whatever returns , use that.
reference global object?!
(function(window, undefined){})(this);
the explanation above code in second answer of referenced post, couldn't understand it, if can explain more (or simpler me), great
update: take @ code ↓
var myelement=document.getelemetbyid("myelementid"); (function(myelement){ /**'this' here 'myelement'???**/ }; })(this);
a common metod following (called namespacing) - created encapsulated scope executing function , returning essential parts need variable:
var yournamespace = (function(window, undefined){ /* private code:*/ var privatevar = "foobar", count = 0; /* stuff want use outside: */ return{ val: 5, publicvar:privatevar, func:function(){return ++count} } })(this);// `this` reference `window` here
this way have access need via yournamespace
variable, while still maintaining privacy , not polluting global object. it's called namespacing , uses closure paradigm. can hand on functions work private (for enclosing scope non-visible) variables.
one reason handing on undefined was, in es3 undefined writable, not case anymore in es5. handing on over this
parameter shortens lookup creating direct reference global window
object in scope. however, cautious - in es5 strict mode this
not window anymore resolves undefined
!! not recommended anymore!
another reason handing on window , undefined these variable names, minifier compress them single letter.
if(myvar == undefined) // compressed to: if(a==x)
edit question:
the this
not change in example, need 1 of following solutions:
(function(myelement){/*your code*/})( document.getelemetbyid("myelementid") ); // or: (function(){ var myelement = document.getelemetbyid("myelementid"); /* code */ })();
Comments
Post a Comment