简体   繁体   中英

Where is the global variable in Node.js hiding?

a = 555
console.log(global.a)

outputs "undefined"

I have been told that global variables in Node go to the object global , but I cannot find it. What I want to do is to write a function that will "display all global variables I (and only I) have created in my program" so that I can find typos. (Recently I declared global variable starCounter instead of assigning to a local parameter startCounter )

UPDATE:

I just realized my actual test file had two more lines and those lines were causing the problem.

a = 555
console.log(global.a)
return; 
var a = Math.pow(4, 3)

But now this puzzles me even more?! Why would local variable assignment that is never reached after the return statement, would screw up the global variable assignment?

I just created this in node v0.8.11. Looks like its working fine. http://ideone.com/2cnEFe

a = 555
console.log(global.a)

Edit: To answer your second question, when you do something like this

var a = 555;

The variable will be created in the local scope. But when you do

a = 555;

the variable will be created in global scope. But when you do.

a = 555;
var a;

The variable will still be created in local scope only. So, in the following code, a will not be created as a global variable. Thats why you get an undefined .

a = 555
console.log(global.a)
return; 
var a = Math.pow(4, 3)

Read an interesting story about missing var in the declaration. HOW ONE MISSING VAR RUINED OUR LAUNCH

 a = 555 console.log(global.a) return; var a = Math.pow(4, 3) 

But now this puzzles me even more?! Why would local variable assignment that is never reached after the return statement, would screw up the global variable assignment?

Because of hoisting . The assignment is never reached and executed, but the variable has been declared in your current scope with the var keyword . Just as function declarations, they are available from when you enter the (function) scope. Your code is equivalent to

var a;
a = 555
console.log(global.a)
return; 
a = Math.pow(4, 3)

You don't need global to find typos in your code.

The best way to do so is to enable strict mode .

There are two ways to do so.

First way is to enable it globally with --use_strict v8 option when starting your node app. I'm not sure that it's a good idea if you're using third party modules which you obviously do.

Second way is to add

"use strict";

at the top of each .js file in your project.

Update

As for your second question, see MDN docs on var .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM