javascript - Why won't my global variable update after this function is called in Node.js? -
my global variable isn't changing after function called in node.js when run application in sublime text 3. when run in bash, changes expected. when replace "global.firstname = 'david'" "window.firstname = 'david'" , run in chrome's console, changes expected.
var firstname = 'simon'; var addsurname = function(){ var firstname = 'gene'; var surname = 'holmes'; var fullname = firstname + ' ' + surname; global.firstname = 'david'; console.log(fullname); }; addsurname(); console.log(firstname); // gene holmes // simon
ultimately, want output
// gene holmes // david
why isn't "global.firstname='david'" statement updating global variable node.js build in sublime text 3?
to use global var in function need define global var
keyword use same var name after alteration of var inside function saved in global var. don't need use of global.
or this.
var firstname = 'simon'; var addsurname = function(){ var firstnametmp = 'gene'; var surname = 'holmes'; var fullname = firstnametmp + ' ' + surname; firstname = 'david'; console.log(fullname); }; addsurname(); console.log(firstname);// output david.
Comments
Post a Comment