开发者

'Global' object in node.js

I am us开发者_如何学编程ing 0.3.1-pre Node.js

Doing this:

typeof global.parseInt

results in

'undefined'

However when pressing [Tab] in the console after typing 'global.' gives a list of functions, including parseInt.

So is parseInt a member of the global namespace or not?


As of NodeJS v0.8.14 global seems to work across modules like the window object does in the browser.

Test:

a.js:

a1 = console.log;  // Will be accessed from b.js
global.a2 = console.log;  // Will be accessed from b.js

require('./b.js');

b1('a: b1');
b2('a: b2');
global.b1('a: global.b1');
global.b2('a: global.b2');

b.js:

a1('b: a1');
a2('b: a2');
global.a1('b: global.a1');
global.a2('b: global.a2');

b1 = console.log;  // Will be accessed from a.js
global.b2 = console.log;  // Will be accessed from a.js

Running a.js outputs:

b: a1
b: a2
b: global.a1
b: global.a2
a: b1
a: b2
a: global.b1
a: global.b2


Apparently, the global object isn't the global object as window is in the browser. It's (according to micheil in #nodejs @ freenode) really only used internally. Something about global closures and whatnot.

parseInt and setTimeout and all those buddies are globals on their own. Not part of any visible global object.


Defining variable in app.js without var, just like myvar='someval' makes it visible inside every .js in your project


FAILS:

if( global[ some_object_i_want_to_exist ] ){ ... }

WORKS:

//: outside of all functions, including IIFE.
const THE_GLOBAL_YOU_PROBABLY_WANT_IS_THIS=( this );

//: Within a function:
const G = THE_GLOBAL_YOU_PROBABLY_WANT_IS_THIS;
if( G[ some_object_i_want_to_exist ] ){ ... }

I am assuming you got to this page about "global" in node.js because you wanted the equivalent of "window" in order to check for globally declared variables. bFunc's solution didn't work for me, as it seems to require that one explicitly does something like:

global.some_object_i_want_to_exist = whatever;

as a pre-requisit to using

global[ some_object_i_want_to_exist ]

EDIT: Looking at my code it seems that the only reason my solution worked is because I used "exports.some_object_i_want_to_exist" somewhere else in the file. Without that, my solution fails. So... I have no clue how to reliable determine if an object exists in a given scope in Node.js.

Here is the documentation on global object: https://nodejs.org/api/globals.html

I am going to leave my answer here because I hear people are more likely to correct you when you are wrong, so maybe someone will correct me with the answer to the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜