For example I have bunch of functions like these:
function a() {
//do something
}
function b() {
//do something
}
// call function a
a();
// call function b
b();
What advantage or disadvantage if I initialized the function this way?
var jslib = {
a: {
init: function() {
//do something
}
},
b: {
init: function() {
//do something
}
}
}
// init function a
jslib.a.init();
// init function b
jslib.b.init();
For example I have bunch of functions like these:
function a() {
//do something
}
function b() {
//do something
}
// call function a
a();
// call function b
b();
What advantage or disadvantage if I initialized the function this way?
var jslib = {
a: {
init: function() {
//do something
}
},
b: {
init: function() {
//do something
}
}
}
// init function a
jslib.a.init();
// init function b
jslib.b.init();
Share
Improve this question
edited Feb 23, 2011 at 0:11
nolabel
asked Feb 23, 2011 at 0:03
nolabelnolabel
1,1574 gold badges18 silver badges26 bronze badges
3
- 1 That's an object of objects, not an array. – BoltClock Commented Feb 23, 2011 at 0:05
- You are right! That is an object b/c it can be written like this {a:{init:function(){}},b:{init:function(){}}}. It is easiest to understand to write it this way: var jslib = {a:{}, b{}} – nolabel Commented Feb 23, 2011 at 0:12
- Uh? What is the difference? It is an object because it is an object (defined with object literal notation). – Felix Kling Commented Feb 23, 2011 at 0:20
3 Answers
Reset to default 5Advantages
- You don't pollute 'global namespace'. E.g., global variable
a
declared anywhere else in Javascript won't hide your function. - You group related functionality together.
Disadvantages
- Code to call a function is slightly longer. (if you consider this to be disadvantage at all)
Although, init
name suggests that those objects have state, so they not only hold functions. In this case, two versions aren't even equivalent.
The primary advantages of defining object literals are not polluting the global namespace and cleaner code organization.
Rebecca Murphey explains the advantages in this blog post:
http://rmurphey./blog/2009/10/15/using-objects-to-organize-your-code/
I prefer to create objects functionally rather than literally because JS functions are first-class objects. Therefore, you can define public methods and properties which can be invoked outside the object, but can also have private variables and functions which are hidden from outside the scope of the object.
function Alphabet() {
// public property
this.letters = 'xyx';
// private variable
var letters = 'abc';
// public method
this.speak = function(){
say("Now I know my ABCs");
}
// private function
function say(message){
alert(message);
}
}
The only real advantage is that you aren't polluting the global namespace with a bunch of extra functions.