If you don't have the behavior associated with the 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 need nothing but a simple data container, go to a simple literal.
If you want to add behavior to your object, you can go with the constructor and add methods to the object at build time or provide a prototype of your class.
function MyData(foo, bar) { this.foo = foo; this.bar = bar; this.verify = function () { return this.foo === this.bar; }; }
A similar class also acts as a schema for your data object. Now you have some kind of contract (through the constructor) which properties the object initializes / contains. A free literal is just an amorphous data frame.
You can also 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 beneficial for encapsulation: ideally, all data + behavior associated with the entity should live together.
Ates Goral Feb 01 2018-11-11T00: 00Z
source share