Reputation: 892
I cannot get why in Browser
code like this:
var gLet = 5;
alert(window.gLet); // 5 (become a property of the window object)
even thought it is old behavior works differently in Node.js:
var gVar = 5;
console.log(global.gVar); // undefined (don't become a property of the global object)
But it works like this in Node.js:
gVar = 5;
console.log(global.gVar); // 5 (become a property of the global object)
This mean that Node.js do not completely support old behavior? Just try to figure out all of it ...
Upvotes: 3
Views: 2108
Reputation: 1
Try this:
(function myModule() {
var gVar = 5;
global.gVar = gVar;
console.log(global.gVar);
})();
Here you need to set first gVar in global object after that you can see the output gVar from global.
Upvotes: 0
Reputation: 944216
Each module has its own scope, so when you declare a variable with var
inside a module, it is scoped there and not globally.
Implicit globals still work as normal. You should activate strict mode so you don't create them.
Upvotes: 3