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

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

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 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