2

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?

Nik
  • 395
  • 1
  • 3
  • 8
  • 1
    Well the word "module" doesn't have an official meaning in JavaScript, so you'll have to explain what you've got. There are different ways of achieving something like a "module". – Pointy Oct 21 '13 at 22:35
  • I am sure you'd be able to find the answer if you look for a related question in Stack Overflow. – Manav Kataria Oct 21 '13 at 22:35
  • How about: http://stackoverflow.com/questions/950087/how-to-include-a-javascript-file-in-another-javascript-file – Manav Kataria Oct 21 '13 at 22:37

2 Answers2

2

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!

Ansikt
  • 1,442
  • 11
  • 13
0

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>
Drew
  • 6,311
  • 4
  • 44
  • 44