Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!