Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda