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

298
Visualizações
Is an exported variable in Javascript considered global?

This is something I've wondered for a while now. Say I have an express application. I have this export in its own file:

// my-var.js
export const myVar = new Thing();

Then I have the server creation where I access that variable:

// index.js
import { myVar } from './my-var';
import { myRoutes } from './my-routes';

function startServer() {
    myVar.doSomething(); /* 1 */

    const app = express();
    app.use('/', myRoutes);
    
    app.listen(port, () => {});
}

Finally, I have my routes, which also use that variable:

// my-routes.js

import { Router } from 'express';
import { myVar } from './my-var';

const router = new Router();

router.get((req, res) => {
    myVar.doSomething(); /* 2 */
    res.json({});
});

So my question is: Is .1 and .2 referencing the same variable? Or has it been instantiated twice? I would kind of think it's instantiated every time the file is imported, because importing a file runs the code in that file. So myVar = new Thing(); is executed every time that file runs.

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

0

The script file is executed once and there is a single result of that file. If any object is exported, all the modules will refer to the same instance of that object.

const myVar = new Thing();

myVar is created only once and then exported.

You can try changing a property in one module and checking that property in another to be sure.

about 4 years ago · Juan Pablo Isaza Relatório

0

That's what we call a singleton pattern package design, when you do it like this:

export const myVar = new Thing()

You only create the Thing instance once, and afterwards everytime you import it, you're importing the same instance, because it's a reference now.

If you want to get a new reference everytime the myVar is imported, change the code

from:

export const myVar = new Thing()

To

export const myVar = () => new Thing()

And when you import it, use it as follows:

import { myVar } from './my-var'

const instance = myVar() // returns a new instance from Thing

// use the instance here, ex: instance.color
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