javascript - JS Global Variable to Local Variable -


this simple question.

i know global variables created when declared outside function (says w3schools.com).

my question is, if create global variable , edit in function, become local? new value given function become global value?

in general, no, editing global not make local:

var myglob = 5; function incglob() {     myglob = myglob + 1; }  incglob(); console.log(myglob); // 6 

however, if pass global variable argument, argument local copy:

var myglob = 5; function incarg(myloc) {     myloc = myloc + 1; }  incarg(myglob); console.log(myglob); // still 5 

note objects passed reference, editing member variables of argument variable changes member variables of original object passed in:

var myglob = { foo:5 }; function editloc(myloc) {     myloc.foo = 6; }  editloc(myglob); console.log(myglob.foo); // foo 6 

finally, note local variable in editloc, above, reference. if try overwrite entire object (instead of member variable), function loses reference original object:

var myglob = { foo:5 }; function clobberloc(myloc) {     myloc = { bar:7 }; }  clobberloc(myglob); console.log(myglob.foo); // myglob unchanged... // ...because clobberloc didn't alter object, // overwrote reference object stored in myglob  

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -