Skip to content
Advertisement

Is it possible to export a function that calls another function defined in the file where the module is imported from?

Example:

// module "my-module.js"    
export default function func1() {
      ...
      func2();
      ...
    }

where func2 is only available in the file where we do:

import func1 from './my-module.js'

function func2() {
  console.log('OK');
}

func1();

Is this possible?

Advertisement

Answer

No, func2 must be defined when you create a func1, otherwise it will be undefined and will throw a runtime exception when func1 will be invoked.

You can pass func2 as an argument of func1 and invoke it inside.

// module "my-module.js"
export default function func1(callback) {
  callback();
}
import func1 from './my-module.js';

function func2() {
  console.log('OK');
}

func1(func2);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement