nolabel
nolabel

Reputation: 1157

Is there any advantage or disadvantage to put JavaScript function into an object and call them when needed?

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

Answers (3)

caseyohara
caseyohara

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

Bryan Kyle
Bryan Kyle

Reputation: 13761

The only real advantage is that you aren't polluting the global namespace with a bunch of extra functions.

Upvotes: 1

Nikita Rybak
Nikita Rybak

Reputation: 68006

Advantages

  1. You don't pollute 'global namespace'. E.g., global variable a declared anywhere else in Javascript won't hide your function.
  2. You group related functionality together.

Disadvantages

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

Upvotes: 5

Related Questions