javascript: what is this: (function(args){})(moreArgs){}); -
this question has answer here:
am still , again , forever trying come grips javascript. @ other scripts inspiration , learning. know is:
(function(args){})(moreargs){});
it's skeleton of jquery. can explain me how works? thanks!
here more of skeleton:
( function( global, factory ) { } )( typeof window !== "undefined" ? window : this, function( window, noglobal ) { return jquery; } );
tldr; (func)(params);
executes function inplace out having assign function separate variable.
lets break code down it's smaller elements. firstly whole code self executing function. consider have anonymous function.
var add = function (a,b) { return + b; };
we can call function like
add(1,2);
however can wrap our function in ()
, call in same way.
(add)(1,2);
both result in add
function being called. because javascript not differentiate between function literals , references anonymous functions can use same format call function literal.
(function(a,b){ return + b; }))(1,2);
it's format code using call outer function. why want call function in way? because namespace, or lack there of. javascript has global mutable namespace. global means of language constructs available in same namespace default scripts executed in. not such problem in namespace mutable. so
array = {};
would redefine array constructor function. other scripts on page using array
stop working if have not finished executing. bad yields unpredictable behaviour. how fix this. 1 way place our entire program in function. when inside closed function no longer in global javascript namespace. in function scope , free redefine array
if feel need(seriously though don't redefine array).
so have our function protects our program form other's running within page have 1 problem. have defined function have not called it. javascript executed it's read. when vm reads first line of js file execute line. not true of code in function. code execute when function called. short hand ()
added end of defined function ensure function called has been loaded vm.
Comments
Post a Comment