Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading