How to Create Data Model Objects in JavaScript

Why it makes sense to use some special facility (constructor function, factory method, class in ES6) for creating objects of Data Model[1] instead of just using object literals and whatever is returned as JSON from server?

Data Model objects typically don't have much behavior hence using something like a constructor function for attaching methods isn't needed. However, I believe there are several other reasons why wrapping Data Model still makes sense.

A Dictionary

Types are useful for documenting the vocabulary you use to implement your app. If you have a concept of user then it is quite useful to have single place serve as a dictionary to look up the properties that it should have.

function User(properties) {
  return _(properties).pick('firstName', 'lastName', 'email');

More Readable Creation

Another good reason for having creation functions is to construct new objects that need to be sent to backend. In some cases we can make the code more readable by having factory methods available for creating different variations of objects of same type. For example, we might have two kinds of recipients in our application - persons and businesses.

This is not so nice:

var business = new Recipient({isBusiness: true, name: 'Fabulous Company'});
var person = new Recipient({isBusiness: false, name: 'Jimmy Smith'});

This looks much better:

var business ={name: 'Fabulous Company'});
var person = Recipient.person({name: 'John Smith'});

Single Place to Change

Finally, it is also good idea to use creation functions to simply mark the places where you create objects of same kind in case you later need to make some changes to them.

All of the above stays valid when choosing how Data Model objects should be created with framework like AngularJS. AngularJS Factory and Service are wrappers to enable DI but nothings stops using them together with any kind of object creation pattern.

Check out this post about AngularJS models if you want to learn more about AngularJS models.

  1. By Data Model I mean the objects used for sending data back and forth between client app and backend as per Model-View-ViewModel. ↩︎