Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
is it possible to change the scope of variables with initially equal scopes?

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

You also could use a module script and store variables using the window object:

<script type="module">
  var variable1 = 'first variable :)';
  // not accessible by others scripts
  
  window.variable2 = 'second variable :)';
  // accessible by others scripts
</script>

<script>
  console.log(window.variable2)
  setTimeout(() => console.log(variable2), 10)
</script>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda