Replacement for "#include", "import" or "use" in pure JavaScript

Hello!

I am new to the object-based language JavaScript. Is there an easy workaround to "include" tested code that exists as a JS-file? What I mean is to do something in a few steps without using jQuery etc. such that the contents of the already tested code in file a.js can be used in b.js.

Thanks in advance for your help!
LVL 1
Ahmet Ekrem SABANSenior IT consultantAsked:
Who is Participating?
 
Tom BeckCommented:
I don't know how else to say it to make it clear to you. ALL in-scope functions in ANY javascript include file are available to ANY script in ANY other javascript include file. In-scope functions inside a javascript include file act as if they were all printed directly in the head section of the page. By "in-scope" I mean not isolated as described in the link I provided.
0
 
Tom BeckCommented:
If b.js is included on the page then all of its functions are available to a.js and vice versa.

You could write your own "include" function -- there are many examples online -- but essentially it does the same thing as including a script block in the head with <script src=...

Here's one example:
function include(filename)
{
	var head = document.getElementsByTagName('head')[0];
	
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	
	head.appendChild(script)
}

Open in new window

Then if you need a particular js file you call the function:
<script>
include("b.js");
</script

Open in new window

0
 
Ahmet Ekrem SABANSenior IT consultantAuthor Commented:
Thank you for your reply! The last code implies that you are using both file contents in an HTML file, as <script>...</script> tags are used there.

What I want is to use any function or object defined inside a JavaScript file in other functions or objects defined in another separate JavaScript file without copying the contents of the first into the second. Is that also possible?

Asking the question another way around, a JavaScript "precompiler" that  merges all my files into one file properly would do the job.
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
Tom BeckCommented:
As I said, all functions in a.js are available to b.js and vice versa if both are on the page. Same as if they were all combined into one file. Same as if all the code was pasted directly in the head of the page. That's why it's a good idea to isolate your variables if the page is complex. A variable with global scope in one js file has global scope in another. If you create another variable with the same name in another js file, there will be a conflict.

http://nicoespeon.com/en/2013/05/properly-isolate-variables-in-javascript/
0
 
Ahmet Ekrem SABANSenior IT consultantAuthor Commented:
<!DOCTYPE html>
<html>
<head>
	<meta charset="ISO-8859-1">
	<title>Numbers</title>
</head>
<body>
	<script type="text/javascript" src="js/Set.js"></script>
	<input id="value" type="text"/><button name="add" onclick="test();">Add</button>
	<div id="output">Results will appear here.</div>
</body>
</html>

Open in new window

This is my HTML page. There will be NO extension here. All the coding is done inside JavaScript (js) files. So, a <script></script> will definitely not help.

What I want is to use the function isArray, defined inside the file LogicalUtils.js as
/**
 * Checks whether the object is an array or not.
 * 
 * @param array Array to be tested
 * @returns {Boolean}
 */
function isArray(array) {
    return (array == null || array == undefined) ? false
    		: array.constructor.toString().indexOf("Array") > -1;
}

Open in new window


inside the Set.js file. (Any solution form the HTML is not of interest.) In other words, I say in Set.js

/**
 * Constructor & definition of the set object.
 */
function Set(input) {
	var self = this;
	// Properties
	self.set = [];
[...]
self.findIndex = function (object) {
		if (self.isValid(object)) {
>>>			if (isArray[/b](object)) {  <<<
				for (var input in object) {
					return self.contains(input);
				}
			} else {
				for (var i = 0; i < self.getSize(); i++) {
					if (object == self.set[i]) {
						return i;
					}
				}
			}
		}
		return -1;
	}

Open in new window


although there is no function isArray defined there.

My question: Is this possible?
0
 
Ahmet Ekrem SABANSenior IT consultantAuthor Commented:
Thank you http://www.experts-exchange.com/members/tommyBoy.html for your patience with me! I could not believe that an '#include' in JavaScript is as easy as this.
0
 
Tom BeckCommented:
That simplicity is a double edged sword. Conflicts can arise from variables of the same name buried deep in an obscure include file resulting in strange behavior that is difficult to troubleshoot. Refer to the link to prevent trouble on complex pages.
Thanks for he points.
0
 
Ahmet Ekrem SABANSenior IT consultantAuthor Commented:
Yessss! And what I found out that the global variables are sometimes misunderstood. I had one called "primes" that is an instance of my object "Set". I changed the code such that nobody accesses it, except the method "getPrimes()", where I added some console logs:
var primes = new Set([2, 3]);
getPrimes();

function getPrimes() {
    console.log("getPrimes(): primes instanceof Set = " + (primes instanceof Set) + ", typeof primes = " + (typeof primes));
    return primes;
}

Open in new window


The first access you can see above was OK, but all other accesses returned that primes was no more an instance of Set. When I packed all in an object, the problem was gone. :->
0
 
Tom BeckCommented:
Good example!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.