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

201
Visualizações
Imported module function in app.js does not have access to class instantiation or app.js variables. Javascript node

I have working code that fails when I try to split it into modules, this is a super simplified version to highlight the behavior I don't understand.

When app.js runs, there is a 'ReferenceError: elf1 is not defined'. I do not understand why func1 does not have access to elf1. I thought maybe changing the func1 to an arrow function away from a standard function would make func1 lexically scoped to app.js.

I realize that in App.js I can declare global.elf1 = new Elf() and then func1.js will have access. However, I don't understand why when an arrow function in a module is invoked within the app.js environment it doesn't have access to the app.js variable environment.

I'm sure this is simple and I'm overlooking some obvious behavior, I thought func1 being an arrow function would have access to app.js environment variables since it was invoked in app.js.

//App.js

let Elf = require('./class');
let func1 = require('./func');

var elf1 = new Elf('jim');

func1();

---------------------------------------
//class.js

class Elf{
    constructor(name){
        this.name = name;
        }
    shout(){
        console.log(`my name is ${this.name}`);
    }
}

module.exports = Elf;

----------------------------------

//func.js

let func1 = ()=>{
    elf1.shout()
}
module.exports = func1;

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

0

func.js has no idea what elf1 is because it's outside of the module scope.

I would just pass in elf1 as a parameter into the func1 function.

//App.js

let Elf = require('./class');
let func1 = require('./func');

var elf1 = new Elf('jim');

func1(elf1);

//func.js
let func1 = (elf1)=>{
    elf1.shout()
}
module.exports = func1;
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