Javascript preferred way to organize object structure
I was curious as to what the standard or common way to organize large object structures was. My first reaction was to organize it like so:
GLOBAL = {
child_1 : {
obj_1 : null,
obj_2 : null,
func_1 : function () {
//Stuff defined here....
}
},
child_2 : {
obj_1 : null,
obj_2 : null,
func_1 : function () {
//Stuff defined 开发者_StackOverflow中文版here....
}
},
child_3 : {
....
};
This is pretty at first, but as the file grows larger and larger and functions get defined it becomes hard to read especially when functions have the same name, such as, "GLOBAL.child_1.func_1" and "GLOBAL.child_2.func_1".
Is there a standard way to structure large applications? One way I could keep it pretty I suppose is to define functions elsewhere and not inside the object hierarchy.
I struggle with this too. Here are some blog posts that I find enlightening:
http://michaux.ca/articles/javascript-namespacing
http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/#more-1789
You don't have to put them all in one giant nested structure. You can do:
var GLOBAL = {};
GLOBAL.child_1 = {
obj_1 : null,
obj_2 : null,
func_1 : function () {
//Stuff defined here....
};
GLOBAL.child_2 = {
obj_1 : null,
obj_2 : null,
func_1 : function () {
//Stuff defined here....
};
GLOBAL.child_3 = {
....
};
Also, I don't understand why you're using generic names like child_1 and child_2. If they have unique functions, then given them unique names that describes their function. If they all have the same functions, then make a re-usable object that you can make multiple instances of. If they're all identical and have no unique pre-declared data, then just initialize them all in a loop.
Your question is very interesting and its answer could be very complex. I will give you some links about that subject (some links refer to jQuery but this is not a limitation):
http://addyosmani.com/blog/large-scale-jquery/
http://blog.rebeccamurphey.com/on-jquery-large-applications
Also, one tip I can give you is to separate your code using this pattern:
// file yoursite.somename.js
var GLOBAL = GLOBAL || {};
GLOBAL.somename = {
someFunction: function() {}
// [...]
};
// file yoursite.someothername.js
var GLOBAL = GLOBAL || {};
GLOBAL.someothername = {
anotherFunction: function() {}
// [...]
};
With that pattern, each functionality is separate into a single file, and each file add one key into the GLOBAL
object. That object will be declared once and only once and will never be overridden.
精彩评论