Tuesday 15 July 2014

javascript - Scope of variables in module pattern -



javascript - Scope of variables in module pattern -

i trying understand how can touch/change/increment privately scoped variable x in next script. i'm using module pattern here, , thought reach , set private variables public homecoming module declared property or method, nil i'm trying working. related: when declare new instance of func vs. accessing func static delcared variable?

class="snippet-code-js lang-js prettyprint-override"> var func = (function() { var x = 1; var squarex = function() { homecoming x * x; }; var addone = function() { x++; } homecoming { x: x, xq: squarex, addone: addone }; }); func().x = 9; // expecting privately scoped x = 9 func().addone(); // expecting privately scoped x = 10 document.write(func().xq()); // expecting 100 actual = 1

the point of module pattern create persistent, private scope invisible outside. unfortunately, every time phone call func, you're creating new scope (with new homecoming functions , closures), of operations discarded afterwards.

instead of calling func multiple times, 1 time setup "module" (you can immediately, iife), , perform operations on result.

class="snippet-code-js lang-js prettyprint-override">var func = function() { var x = 1; // private variable var squarex = function() { homecoming x * x; }; var addone = function() { x++; }; homecoming { // note, can't "x: x," // since create copy; // have utilize properties x() { homecoming x; }, set x(val) { x = val; }, xq: squarex, addone: addone }; }; var funcmodule = func(); funcmodule.x = 9; funcmodule.addone(); document.write(funcmodule.xq());

note reason need explicit getter , setter x module property because need able modify inner (hidden) variable x. properties available in modern browsers, including ie9+. if you're working in ie8 or below, you'll need define explicit getx , setx methods, , phone call them straight (you won't able funcmodule.x = 5).

javascript

No comments:

Post a Comment