nemo_87 nemo_87 - 1 year ago 98
Javascript Question

Call function from another js file when using iife pattern?

Is it possible to call function that is in one js file and it is made public by usage of iife pattern, in another js file?
For example, this is some validationScript.js file:

var ValidationNamespace = function ()
var nameValidation = "";
var testValidation = "";

validateIfNameAlreadyExistsInTable : function(currentNameValues)
for(var i=0; i < currentNameValues.length ; i++)
if(document.getElementById("tbName").value == currentNameValues[i])
var nameVal = "Name already exists in table!";
document.getElementById("nameVal").innerHTML = nameVal;
return false;
document.getElementById("nameVal").innerHTML = "";
return true;

And I have another file, lets say script.js

Is there some way to call function
from some script.js function?

The problem is that it is undefined when I try to call it:

enter image description here

I have index.html where I am referencing both .js files like this:

<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="validationScript.js"></script>

Answer Source

Yes, because the IIFE returned an object that exposes the function, and the file saves that object as ValidationNamespace, which is a var declared globally and thus a global variable.



Re your edit, you probably want to load the scripts in the other order, first validationScript.js then script.js:

<script type="text/javascript" src="validationScript.js"></script>
<script type="text/javascript" src="script.js"></script>

Scripts are loaded and run in the order you give them (unless you use async or defer). So unless your code in script.js is waiting for some other event, it'll run before validationScript.js is loaded.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download