0

I have a class in a JavaScript file

class engine
{
   constructor(a)
   {
      this._a = a;
   }

   foo = function()
   {
      console.log(this._a);
   }
}
module.exports.engine = engine;

Then in my NodeJS file I do

const engine = require('./engine.js');

Now my question is, how can I call foo() from my class in the NodeJS file with using the constructor new engine('bar')?

Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102
  • 1
    Some conventions: start that class name with an uppercase letter, because that's what classes are expected to use. Lower case implies it's a function. Also if you're using `this`, there is no reason to use an underscore. `this.a = a` in your constructor, then `console.log(this.a)` in your foo. Finally, why use the instance field syntax `foo = function() { ... }` instead of normal class method syntax `foo() { ... }`? It's just a class function, declare it as such. – Mike 'Pomax' Kamermans Mar 03 '20 at 01:09
  • @Mike'Pomax'Kamermans - re the underscore - I think there is/was a convention that "properties" beginning with `_` are "private" or something (obviously they are not though) - ref: https://stackoverflow.com/questions/4484424/underscore-prefix-for-property-and-method-names-in-javascript – Jaromanda X Mar 03 '20 at 01:20
  • Does this answer your question? [How to access a method from a class from another class?](https://stackoverflow.com/questions/39175922/how-to-access-a-method-from-a-class-from-another-class) – Heretic Monkey Mar 03 '20 at 01:24
  • That's only a conventioon _in Python_ @JaromandaX, no such convention exists in JS, and the proposal for private properties uses `#`. – Mike 'Pomax' Kamermans Mar 03 '20 at 05:13
  • @Mike'Pomax'Kamermans - go back many (and I mean many) years, and it definitely was a convention in javascript - I did link to the wrong post though :p – Jaromanda X Mar 03 '20 at 08:11
  • yeah but now we're talking a time when class syntax didn't even exist, so it'd be a weird situation where this person learned classes from somewhere _and_ using an underscore. – Mike 'Pomax' Kamermans Mar 03 '20 at 17:11

2 Answers2

0

You have to use instantiation using new keyword

const engine = require('./engine.js');

const myEngine = new engine('Hello world!'); // Now myEngine is instance of engine class
myEngine.foo(); // You can now use foo() method
boosted_duck
  • 420
  • 3
  • 14
0

you should export file as defalut like that

module.exports = engine;

instead of

module.exports.engine = engine;

as in second example you export your file as {engine} and when import you should import as

const {engine} = require('./engine.js');

but when you use export like first example you can export and import like that

// engine.js
module.exports = engine;



// index.js
const engine = require('./engine.js');

const myEngine = new engine('a'); 
myEngine.foo(); // You can now use foo() method