1

I have an module exported as the following, I want to call function in another is that possible in that case

module.exports = {
  first:() => {
    // this is my first function
  },
  second:() => {
    // I want to call my first function here
    // I have tried this 
    this.first()

  }
}
5
  • you can define the functions before exporting and reuse them however you want. Commented Jan 17, 2021 at 11:38
  • Ok I know this way but I thought there is might be another way to do it as it is Commented Jan 17, 2021 at 11:41
  • 1
    Wouldn’t just using a normal function instead of an arrow function fix the issue? Commented Jan 17, 2021 at 11:49
  • I have used the function keyword but it didn't solve it @strahinja Commented Jan 17, 2021 at 12:07
  • It give me this error this.first is not a function @strahinja Commented Jan 17, 2021 at 12:11

2 Answers 2

1

You can define module.exports at first in a variable and use it in second as follows:

First file (other.js):

const _this = (module.exports = {
  first: () => {
    console.log("first");
  },
  second: () => {
    _this.first();
  }
});

Second file (index.js):

import other from "./other";

other.second();

Output:

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

Comments

0

You can access it from the other module like this

const {first, second } = require('./module2');
first();
second();

or

const collectedFunctions = require('./module2');

collectedFunctions.first();
collectedFunctions.second();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.