Reputation: 1157
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();
Upvotes: 2
Views: 1733
Reputation: 83
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.com/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);
}
}
Upvotes: 3
Reputation: 13761
The only real advantage is that you aren't polluting the global namespace with a bunch of extra functions.
Upvotes: 1
Reputation: 68006
Advantages
a
declared anywhere else in Javascript won't hide your function.Disadvantages
Although, init
name suggests that those objects have state, so they not only hold functions. In this case, two versions aren't even equivalent.
Upvotes: 5