Literal notation vs. constructor in JavaScript
February 7, 2012 8:00 AM   Subscribe

Literal notation vs. constructor: Which one should I use to create an object in JavaScript?
posted by markcmyers to Computers & Internet (5 answers total)
 
It would depend on how that object is used:

If the object is just a plain old data I would use literal notation.

If the object had a life cycle, depended on another objects state, or had state of its own I would use a constructor.

I am no JavaScript guru though, that's just my take on it.
posted by rickim at 8:08 AM on February 7, 2012


Best answer: You haven't provided enough information here to answer that question. As someone who writes a lot of complicated JS for a living I can tell you both.

Generally things written completely literal notation are usually used as singletons. These are very common in JS apps. Constructors are used in cases where you're following more of a classical OOP pattern where you want to create multiple similar "objects" from a base "class" (realizing Javascript is prototypical not classical OOP).
posted by bitdamaged at 8:45 AM on February 7, 2012


(I should say too, one is not "better" then the other, they have different uses)
posted by bitdamaged at 8:48 AM on February 7, 2012


Crockford says that the only time you should use 'new' to create an object is when you're actually using a constructor.
posted by zsazsa at 9:29 AM on February 7, 2012


I would go with literal everywhere you can get away with it - easier to use, easier to read.
posted by Artw at 1:54 PM on February 8, 2012


« Older Caution section in factsheet   |   Do what you like well enough Newer »
This thread is closed to new comments.