0

I have app.js

var List = {};
var Entity = require('./entity.js');
var main = new Entity(); // should be changed List
console.log(List) // still empty

and entity.js

class Entity {
  constructor(){
    this.id = Math.random();
    List[this.id] = this; // List == undefined
  }
}
module.exports = Entity;

How can I use List as global variable?

2 Answers 2

2

Just import List in entity.js:

At the end of app.js:

module.exports = List;

At the start of entity.js:

const List = require('./app.js');

If your app.js needs to export something else as well, then export an object with a List property instead:

At the end of app.js:

module.exports.List = List;

At the start of entity.js:

const List = require('./app.js').List;

You could also consider putting List into its own module that both app.js and entity.js import.

Don't make List a global variable, if at all possible - work with the module system instead, explicit dependencies without global pollution is one of a module system's big advantages.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to pass List param and access in constructor ...

new Entity(List);

constructor(List){
 ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.