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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
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
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

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
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.