Whats the right way to use the JavaScript scope? -
Whats the right way to use the JavaScript scope? -
i have question. need know whats right way utilize javascript scope.
i have var this: var myvar;
want create function modifies var. right way:
function a() {myvar = 12;} a();
or
function b(item) {item = 12;} b(myvar);
my goal is, dont want create myvar
global.
the js way of modifying var not global, shared between multiple functions/blocks of code through utilize of closure:
var myfunc = (function() { var myvar = 1; homecoming function() { console.log(myvar++); }; }()); myfunc();//logs 1 myfunc();//logs 2 console.log(myvar);//<-- undefined, reference error
if, in snippet, variable used 2 functions, can write this:
var mymodule = (function() { var myvar = 1, mod = {};//object mod.funca = function() { console.log(myvar++); }; mod.funcb = function() { mod.funca();//or this.funca console.log(myvar); }; homecoming mod;//assign object mymodule }()); mymodule.funca();//logs 1 mymodule.funcb();//logs 2, first, logs 3 mymodule.funcb();//3, 4 console.log(mymodule.myvar);//undefined!
the beauty of value of myvar
hidden. var can accessed through functions returned iife. there no global variable, no property, value does exist far funca
, funcb
concerned. rest of code can utilize var myvar
without affecting how mymodule
works.
how closures work, , how js resolves variable names have explained before. here's couple of links might useful you:
on closures. read through part of reply graphs this answer has useful links @ bottom.
javascript
Comments
Post a Comment