How does a (function (){})(); work?(Javascript structure) -
this question has answer here:
i'm using an example project and, while playing around , going javascript code, found function:
(function () { ... ... lot of code ... ... ... scrolltopage : function (page, time) { time = time || 0; if (page < 0) page = 0; else if (page > this.pages.length - 1) page = this.pages.length - 1; this.changetarget(this.pages[page]); this.scrollto(-page * this.pagewidth, this.y, time); } ... ... })();
i know how works. idea of why want use this, it's because want use scrolltopage
function outside of function navigate on button click. experience have in javascript in unity3d different of web scripting i'm trying out now.
so this:
(function () { ... ... lot of code ... ... ... scrolltopage : function (page, time) { time = time || 0; if (page < 0) page = 0; else if (page > this.pages.length - 1) page = this.pages.length - 1; this.changetarget(this.pages[page]); this.scrollto(-page * this.pagewidth, this.y, time); } ... ... })(); function mybuttonfunction() { scrolltopage(1); }
the way written, define anonymous function (notice there no name in it) , invoking right away. used in cases when need write chunks of code in functions , invoke right away.
update: in example, code inside (function(){})(); probably executed when site starts (you need see place chunk of code placed inside website). in fact, kind of "assigns" function object's member variable (i suppose code part of object declaration in part of code don't show, example var o = {....}
) - think of setting function new object's member variable in order use invoke "inner" function. later, in button function, variable can used invoke "inner" function (which has private scope inside outter function). used assign function callbacks button use later inside site.
Comments
Post a Comment