首页 > 解决方案 > 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?

标签: javascriptfunctionimportexportes6-modules

解决方案


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);

推荐阅读