0

Is there an option to get a reference to the whole script variables?

lets assume this code:

const a=n=>n+1,
b={};
let c=3

I wonder if I can access all variables by one reference, like this vars:

vars.b //{}
vars[varName]

so that I'll be able to pass it to other sub modules easily instead of creating a manualy associative array with the variables of the script

iTaMaR
  • 189
  • 2
  • 10
  • as far as i know i dont think you can just simply use something like `vars[varName]` to get all the variables in the whole file – I_love_vegetables Jul 25 '21 at 08:42
  • Why don't you encapsulate all variable you need into object and send the object? – Alireza Ahmadi Jul 25 '21 at 08:44
  • this should help: [can-i-access-variables-from-another-file](https://stackoverflow.com/questions/3244361/can-i-access-variables-from-another-file) – ahsan Jul 25 '21 at 08:47

3 Answers3

0

It is possible only to some limit.

There is globalThis variable acting as a container for all top-level variables. And also in every function arguments variable is available holding everything passed to function in the current call.

I'm not aware of anything similar for function-/block-scope variables

Vasily Liaskovsky
  • 2,248
  • 1
  • 17
  • 32
0

I think you can assign those variables to a JSON object and then export the JSON object as follows so that you can reference all the variables in other file.

// scripts.js file

let a = n => n+1;
let b = {};
let c = 3;

module.exports = { a, b, c };

// index.js file

const scripts = require('./scripts');

console.log(scripts.a(4));
console.log(scripts.b);
console.log(scripts.c);
Salvino D'sa
  • 4,018
  • 1
  • 7
  • 19
0

No, there's no way to programatically get access to the environment record of a given function/scope/closure. To do something like this, the best way would be to define the variables as part of an object or Map in the first place. Instead of

const a=n=>n+1,
b={};
let c=3

do

const theNamespace = {
  a: n=>n+1,
  b: {},
  c: 3
};

and pass theNamespace around.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320