Home > Software engineering >  Does imported functions from the same source, have access to their source global variables?
Does imported functions from the same source, have access to their source global variables?

Time:06-01

OK i searched every site i knew, using every keyword i knew, but i found nothing close the subject i searched about, maybe the whole question is wrong, but anyway...

let's say we have a module named Index.js, which contains a STORAGE and two functions responsible for reading/writing to STORAGE.

var STORAGE = []

function writeStorage(data) {
  STORAGE.push(data)
}

function readStorage(data) {
  //find data in STORAGE... and return result as RES
  return RES
}

Now, inside a file named write.js, we import writeStorage().

While in another file named read.js, we import readStorage().

And this is where the question rises,

Does imported functions from the same source, have access to their source global variables ?

i.e, can we modify STORAGE in index.js, using writeStorage() which we imported in write.js ?

and read STORAGE changes from read.js using readStorage() ?.

CodePudding user response:

Short answer: Yes, that's possible.

CodePudding user response:

I want to provide clearer answer about that. There are two scopes for functions: lexical, and dynamic. Dynamic means, a function will search variables in the are, there it was called:

let someVar = 'global';

function dynamicScope () {
    someVar = 'dynamic';
    console.log(somevar);
}

dynamicalScope (); // will display 'global'

Lexical means, the function will seach variables where it was writted/delcared:

let someVar = 'global';

function lexicalScope () {
    someVar = 'lexical';
    console.log(somevar);
} 

lexicalScope(); // will display 'lexical'

But in JavaScript, there is no way to use dynamic scope, so all function will search variables where it has been declared/written.

DO NOT PAY ATTENTION ON DETAILS, IT'S JUST A PSEUDO-CODE.

  • Related