I am getting confused over which way I should be creating an object in javascript. It seems there are at least two ways. One is to use object literal notation while the other uses construction functions. Is there an advantage of one over the other?
Share
If you don’t have behaviour associated with an object (i.e. if the object is just a container for data/state), I would use an object literal.
Apply the KISS principle. If you don’t need anything beyond a simple container of data, go with a simple literal.
If you want to add behaviour to your object, you can go with a constructor and add methods to the object during construction or give your class a prototype.
A class like this also acts like a schema for your data object: You now have some sort of contract (through the constructor) what properties the object initializes/contains. A free literal is just an amorphous blob of data.
You might as well have an external
verifyfunction that acts on a plain old data object:However, this is not favorable with regards to encapsulation: Ideally, all the data + behaviour associated with an entity should live together.