'Global' object in node.js

前端 未结 4 2117
难免孤独
难免孤独 2020-12-06 03:05

I am using 0.3.1-pre Node.js

Doing this:

typeof global.parseInt

results in

\'undefined\'

Howeve

相关标签:
4条回答
  • 2020-12-06 03:27

    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
    
    0 讨论(0)
  • 2020-12-06 03:29

    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 讨论(0)
  • 2020-12-06 03:41

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

    0 讨论(0)
  • 2020-12-06 03:50

    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.

    0 讨论(0)
提交回复
热议问题