Nik
Nik

Reputation: 405

JavaScript 'Import' a module into another module

I'm currently messing around with JavaScript to try and understand the language more. I want to make two different modules, one with generic helper functions and the other with specific functions to the problem.

How can I access functions from one module to another?

Upvotes: 2

Views: 2507

Answers (2)

Drew
Drew

Reputation: 6639

You would simply place the various functions into two separate files then reference them in a "sandbox" HTML page as follows:

helper.js

function helper_function() {
    alert("this is a helper function");
}

specific.js

function specific_function() {
    alert("this is a specific function");
}

index.html

<html>
<head>
    <script src="helper.js"></script>
    <script src="specific.js"></script>
</head>


<body>

<script type="text/javascript">
    helper_function();
    specific_function();

</script>
</body>
</html>

Upvotes: 0

Ansikt
Ansikt

Reputation: 1552

You have two options here. Both are fairly popular, so it's up to you which you choose.

The first is to define your helper module in the scope of your application module's parent:

var helpMod = (function(){
  return {foo:"bar"}
})();

var appMod = (function(){
  console.log(helpMod.foo);
})()

And the second is to directly import the module as a parameter to the closure function:

var helpMod = (function(){
  return {foo:"bar"}
})();

var appMod = (function(h){
  console.log(h.foo);
})(helpMod);

Direct imports are more explicit, but taking advantage of scoping can be easier - so long as you're comfortable with that variable in the global scope!

Upvotes: 2

Related Questions