JavaScript object literals are very handy, they are just key-value pairs. Very convenient to implement dictionaries and also a very simple implementation of the Singleton pattern:
var message = {sender: 'bob', body: 'hello'};
Duck typing is a technique I use very often as I test-drive my JavaScript code and object literals make it very easy. But overusing them lead to several problems:
- Feature envy code smell
- Anemic models
- Refactoring difficulties
I am no longer using object literals in my tests because when I need to add methods to those objects, I need to change too many tests. Also, exposing all those fields lead to feature envy rapidly, producing semantic coupling sooner or later. Although tests are written fast with object literals, I prefer to encapsulate the fields into business objects.
function Message(sender, body){
this.sender = sender;
this.body = body;
}
var message = new Message();