0

I have a file. a.js

class A{
  constructor(name){
        this.name = name;
    }

  displayName(){
    console.log(this.name);
  }
}
module.exports = A;

Another file common.js

const A = require('./a');
exports.A;

Another file b.js

const common  = require('./common');
var a = new common.A('My name is khan and I am not a terrorist');
a.displayName();

I am getting an error A is not a constructor. Please help, how can get it done. Please forgive my silly mistakes, I am newbie.

6
  • 1
    well in a.js you should be doing : module.exports = A Commented Apr 20, 2017 at 19:02
  • and to be consistent in common.js module.exports = A Commented Apr 20, 2017 at 19:05
  • I am sorry, its module.exports = A only. Let me edit in question. Commented Apr 20, 2017 at 19:07
  • @lomboboo added module.exports = A; still the same error. Commented Apr 20, 2017 at 19:11
  • @Imran see my answer below... Commented Apr 20, 2017 at 19:12

1 Answer 1

3

Here are the fixes that you should make...

In the a.js file, you're exporting Render, however, it should be A instead...

class A {
    constructor(name) {
        this.name = name;
    }
    displayName() {
        console.log(this.name);
    }
}
module.exports = A;

In your common.js file, you have to export an object that consist of the common classes/functions/variables, or whatever, like the following:

const A = require('./a');
const someOtherVariable = 'Hello World!';
module.exports = {
    A: A,
    someOtherVariable: someOtherVariable,
};

Comment: the reason you "have to" is because you want to use the A class with the following syntax: common.A... Assuming the name of the file is common, you will probably export more than just that one class, so package them into an object...

Lastly, in the b.js file, you can then use the common.A syntax to extract the class you are looking to use...

const common = require('./common');
const a = new common.A('My name is khan');
a.displayName();
console.log(common.someOtherVariable); // Hello World!

Hope this helps.

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

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.