0

So like wading into a beach pool and finding it has a riptide, my journey in JS programming has gotten complicated quite quickly.

I have an application I am building that has a class, cataloque.js that loads and renders data. It currently does a few things that I would rather it didn't such as put up dialogs for the user.

It is imported into a file, core.js, that handles my user interaction and building parts of the UI

I want to take those user alert functions and put them into another class but then I run into some problems. A class can't be a module (as the this. operator is set to window. in modules) so I can't import another class into catalogue.js.

I also can't seem to reference functions in the core.js file from my class.

So what is the best way to structure this so I can import multiple classes and still have some way of having them 'talk' to the core.js functions?

To help illustrate:

core.js

  • imports catalogue.js creates new class variable
  • imports dialogs.js creates new class variable

So if I have code in the cataloque class that needs to alert the user and I want to call code in the dialog class how do I mediate that communication?

So catalogue calls core which then calls dialog to show the user a dialog

Do I need to declare a namespace in core.js? Is this just a crazy way to build something in JS?

Also, I have done a lot of searches for articles in this vein but I assume that since the class structure has undergone changes recently that there are not a lot of references available via searches so any good reading suggestions would be quite helpful.

Zac
  • 23
  • 6
  • Sure you can import classes from modules. If `this` is an issue, use `.bind` or arrow functions instead. (can't go into detail without seeing more code) Also, IMO a common mistake new JS devs make is overusing classes - plain functions work just fine in most situations, in my experience, and usually don't have issues with `this`. – CertainPerformance Nov 18 '21 at 15:25
  • For more concrete info, we'll need to see the code. – CertainPerformance Nov 18 '21 at 15:25
  • You can import a class from a module but can you import a class into another class? My thoughts were that you can't because of the way this. is scoped in a module? – Zac Nov 18 '21 at 16:16
  • See the linked canonical for how to deal with issues with `this` – CertainPerformance Nov 18 '21 at 16:17
  • It's [generally recommended](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) to name modules `*.mjs` so that they are easily recognized as modules, as opposed to `*.js` include files of regular JavaScript. – RBarryYoung Nov 18 '21 at 16:27

0 Answers0