javascript: How do you use a function from the importing module in a function from the imported module/file

So I have a module

import {childFunction} from './child.js'
var parent = (function(){
  function parentFunction(){
    alert('parent hello');

   }


})();

Then in child.js

export function childFunction(){
  alert('child hello');
  parentFunction();
}

When I try to run this it says parentFunction is undefined. Am I misunderstanding a concept here or am I using the wrong functionality?

Is it possible to do what I’m trying to but in a different way?

>Solution :

Two modules cannot import each other

That creates a circular dependency that cannot be resolved.

You could, instead, pass the parent function to the child function

That allows you to get around this.

child.js:

export function childFunction(parentFunctionPart2){
  alert('child hello');
  parentFunctionPart2();
}
parent.js:

import {childFunction} from "child.js"

function parentFunction(){
    childFunction(parentFunctionPart2)
}

function parentFunctionPart2(){
    // stuff that needs to provided to childFunction
}

Leave a Reply