Issue
i want to know if i can make the scope of a varible go out of a module script tag, or if i can export it in some way and import in another script tag.
my current code is something like this:
<script>
var variable1 = 'first variable :)';
var variable2 = 'second variable :)';
</script>
<script>
// i want to be able to access variable1 here, but not variable2
</script>
would something like this be possible?
i already tried var
, let
, const
and window.
, but they make no difference.
i also tried to make the first script a module, but then i couldn’t access variable1
, and (i think) there’s no way to use import/export.
notes:
i only want to separate the scripts into separate files if there is no other option.
Solution
Since variable1
and variable2
are defined in the same scope (at the top level), there’s no way to access only one but not the other elsewhere – unless you changed the first script tag to something like
<script>
var variable1 = 'first variable :)';
(() => {
var variable2 = 'second variable :)';
// do stuff with variable2
})();
// variable2 cannot be seen outside
</script>
i only want to separate the scripts into separate files if there is no other option
It’s a very good option that you should consider if you’re making something reasonably professional and the code to be written isn’t trivial. I highly recommend it, it makes the process of writing and maintaining code much, much easier. Yes, it does take some time to figure out and get used to, but it’s worth it, IMO.
Answered By – CertainPerformance
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0