I have created a javascript file with some utility functions. How do I "include" to those functions from another javascript file? Also if I create a global variable inside one of my javascript files, can the utility functions see that variable if they are called?

Recommended Answers

All 2 Replies

Simply include all .js file's that you need in your document.
Here's simple demo to clear things out:
saying i have 3 .js files:
three.js

var varThree = varTwo; 
// varThree variable is not accessible to two.js and one.js
// But varThree can access variables from the two other .js

two.js:

var varTwo = varOne; // this varible is not accessible to one.js but accessible to three.js

one.js

var varOne = "Hello World"; 
// This variable is accesible to all other .js

// all your .js file's must be in an ascending form when you load them in your document's to access each variables.

Now let's see the output:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>Test Page</title>
<script type="text/javascript" src="one.js"></script>
<script type="text/javascript" src="two.js"></script>
<script type="text/javascript" src="three.js"></script>
<script type="text/javascript">
window.onload = function() {
alert( varThree );
}
</script>
</head>
<body>
<div id="content">

</div>
</body>
</html>

Thanks for the clear illustration. It works fine and was helpful in helping me start to get a feel for javascript (compared to compiled languages for example).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.