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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With