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?
Objects created using object literals are singletons. This means when a change is made to the object, it affects that object across the entire script. Object defined with a function constructor let us have multiple instances of that object. This means change made to one instance, will not affect other instances.
Now the question is when should we be using Literal notation and constructor notation. The point is when we need only one instance with the same values then we can go with the literal notation else if we may need multiple instances, like the instance of a class, we can go for the constructor notation.
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....
The main difference here is what you can do with it. With the constructor function notation you create an object that can be instantiated into multiple instances (with the new keyword), while the literal notation delivers a single object, like a singleton.
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.
var data = { foo: 42, bar: 43 };
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.
function MyData(foo, bar) { this.foo = foo; this.bar = bar; this.verify = function () { return this.foo === this.bar; }; } // or: MyData.prototype.verify = function () { return this.foo === this.bar; };
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 verify
function that acts on a plain old data object:
var data = { foo: 42, bar: 43 }; function verify(data) { return data.foo === data.bar; }
However, this is not favorable with regards to encapsulation: Ideally, all the data + behaviour associated with an entity should live together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With