I have the following script:
/* script.js */
var bar = "bar1";
function foo() {
console.log('this.bar: ' + this.bar);
console.log('global.bar: ' + global.bar);
}
foo();
Running node script.js
returns:
this.bar: undefined
global.bar: undefined
However, from inside the node command line environment, reproducing the same script returns:
this.bar: bar1
global.bar: bar1
Further, if I change my variable declaration from var bar = "bar1";
to global.bar = "bar1";
both methods of running the above code return:
this.bar: bar1
global.bar: bar1
What's the difference? Is global variable assignment somehow different when running a script vs reproducing a script in the same environment?