Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically access a global variable in Node?

In browser-based JavaScript, you can do something like this:

var foo = "foo";

(function() {
    var foo = "bar";

    console.log(foo);
    // => "bar"

    console.log(window["foo"]);
    // => "foo"
})();

Is there any way to do something similar in Node, which lacks a window object?

like image 770
Hydrothermal Avatar asked Apr 27 '26 14:04

Hydrothermal


1 Answers

If you want an environment agnostic approach, for example, when writing code to work on both the browser and Node.js, you can do something like this in global code at the top of your JavaScript file:

var globalObject = typeof global === "undefined" ? this : global;

and then use globalObject similar to how you would window in the browser context and as you would use global in the Node.js context.

Note that you must declare a variable without var for it to be part of the global object in Node.js.

like image 131
Peter Olson Avatar answered Apr 30 '26 05:04

Peter Olson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!