JavaScript - Advantages of object literal

Viewed 24638

I've read that rather than simply writing a bunch of functions, I should use object literal.

Can someone explain what the advantages of object literal are with examples, because I don't understand thus far.

Thanks

4 Answers

Ive always used object literals because they are a clear way to organise code. Which is why I don't like prototype, it's too messy.

Functions don't polute the name space as someone mentioned above any more than object literals.

You could easily write a literal like

var obj = {}
var find = function(elem) { /* find code */ },
var doSomething = function() { /* doSomething code */ },
var doSomethingElse = function() { /* doSomethingElse code */ }

which would polute by creating lots of global objects the same the same as the functions. similarly you could do:

(function() {
function find(elem) { /* find code */ },
function doSomething() { /* doSomething code */ },
function doSomethingElse() { /* doSomethingElse code */ }
})();

which would not create those global objects (everything is an object in JS)

that way you still don't create loads of global objects.

To my mind object literals have two advantages. One they are used by many plugins such as jQuery so people are familier and they are easy to read. Making them easy to pass through data into a plugin. It's easy to create both public and private methods....

They can be slow though as every time you create an instance of the object all it's methods are duplicated. It's my understanding that that isn't the case with prototype as you have one copy of the methods and new ojects simply reference the prototype.

I could be wrong of course...

Related