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;
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.