Reputation: 85
We have a global object in javascript that we can refer to using window
for accessing any global variable. But how to refer to the module scope object where all the variables in that module are stored?
Actually, I need to refer to an imported object in the module using string. If it was a global variable, I could've simply done this,
let object_I_want = window[string];
But for module, I can't find the reference for such object. I also tried using this
,
var scope = this;
somefunction(){
let object_I_want = scope[string];
}
But, this
is undefined inside module context according to the specification. Is there a way to reference the module scope/module object like window
.
Upvotes: 2
Views: 1023
Reputation: 33701
I think another way to word your question might be: "How can I access scoped variables using strings?", and the answer is "It's not possible in JavaScript".
If you truly need this kind of dynamic flexibility with your values, you must assign them all to a top-level object (and you must export that object from your module if you want to access it and its values outside the module). Or use eval
, if supported in your environment.
Upvotes: 2
Reputation: 664356
There is no such object for modules. The module scope is like a function scope - an environment record that you cannot access from javascript, you can only use it to declare variables.
There is an object that holds all the export
ed names of a module (which you can get by doing a namespace import * as … from …
), but this doesn't seem to be what you want.
Upvotes: 1