Reputation: 305
I have a very large number of objects that I want to declare. However, I'd like to do so in an auxiliary javascript file to keep the clutter down in my primary javascript file. How can I do this so that the code in the main javascript file will still have access to the objects that I am creating in the auxiliary file?
Upvotes: 1
Views: 4928
Reputation: 2376
Here's basically what I do (this may not work out of the box, but it's pretty close to how it actually works for me):
1) Create a JS file with a global scope and declare an object to HOLD all those other objects:
global.js
var Registry = {};
Registry.object1 = { name: "Jack", age: "30" };
Registry.object2 = { name: "Sharon", age: "28" };
2) Create a secondary (auxiliary) that USES those objects:
people.js
(function() {
console.log("Hi, "+Registry.object1.name+"! Meet "+Registry.object2.name+"! She's only "+Registry.object2.age+" years old!");
});
which should output: Hi, Jack! Meet Sharon! She's only 28 years old!
You would include global.js
on every page, which contains every global object, and then only use the auxiliary JS files when you need them.
The main reason why I created the Registry object to hold the others is to make sure that no other objects anywhere else can conflict. If I have another object named "object1" somewhere else, you could have some problems, but if you stick them inside another holder object, it makes sure that there aren't any conflicts. (i.e., Registry.object1
is different from object1
)
It's useful to note that objects can contain functions (which effectively makes them classes), so you can have global classes to use.
That's basically how I do it. Hope that helps.
Good luck! :)
Upvotes: 0
Reputation: 13820
Simply declare the objects outside the scope of a method and they will be accessible globally.
Auxiliary Script:
object myObj;
object myObj;
$(document).ready(function() {
// Do your manipulations here if needed.
});
Primary Script:
$(document).ready(function() {
myObj.property = "value";
});
Also, reference your "auxiliary" file before your primary one in your markup page like so:
<head>
...
<script src="js/auxiliary.js" type="text/javascript"></script>
<script src="js/primary.js" type="text/javascript"></script>
</head>
Upvotes: 2