In this post we will see how we can use Objects Literals when doing JavaScript OOP. We have seen how we can use function constructors to deal with objects, but JavaScript is an unbelievable flexible language, which offers different ways to solve the same problem.

Object Literals

Objects literals are probably the simplest way to create an object. An Object Literal is a comma separated list of name/value, wrapped inĀ  curly brackets like this:

var person = {
    name: "John",
    age:35,
    greet: function ()
    {
          console.log("Hello!");
    }
}

Singletons with JavaScript Object Literals

Notice that differently from when we use function constructors, we are defining and at the same time instantiating the object. We would use like this:

person.greet();

Output:

>> Hello!

We have also effectively created a singleton. If we try to create a different instance of the same object like this, we will get unexpected results:

var person = {
    name: "John",
    age:35,
    greet: function ()
    {
          console.log("Hello!");
    }
}
var child = person;
child.name ='Bob';
console.log(child);
console.log(person);

Output:

Object { name: "Bob", age: 35, greet: person.greet() }
Object { name: "Bob", age: 35, greet: person.greet() }

Oops, when we modified the attribute name of child, we modified also the same attribute in person. This happens because when we assigned child, we did not create a new object, but just a reference pointing to the person object.

We could circumvent that by just cloning the object person: that is creating a copy of the object, and assigning it to our child variable. Notice, though, that if we were to do that, every time we cloned a new object, that object would have a copy of the functions, which is is not efficient from a memory usage point.

If we are planning to create multiple instances of a same object, we could do it using function constructors, and making use of the prototype property, or as of ES6 using JavaScript classes.

Practical uses of Objects Literals, and Singleton in JavaScript

In programming we use singletons whenever we want to have a unique instance of an object, that many times (although not always) we want to access globally.

An interesting use of Singleton in JavaScript is to simulate the use of namespaces: differently from Java, or C# JavaScript does not come with namespaces, or packages out of the box.

Take for example this C# library:

namespace UtilsLibrary
{
	class LoggerUtils {  

		public static void printMessage(string message){
			//code here
		}

		public static void logMessage(string message){
			//code here
		}
	  }
}

In plain JavaScript it would look like this:

function printMessage(message){
	//code here
	}

function logMessage(message){
	//code here
	}

Functional, but there are a couple of ugly things in this solution:

  • We are polluting the global space
  • Our functions may be overwritten by different library

Indeed, if we were to add a third party JavaScript library that casually has a logMessage function, we would end up inadvertently overwriting our own function. In the long term that kind of programming results in code difficult to maintain, and to debug.

Lets see how we can solve this problem applying what we have learned about Singletons, and Object Literals:

// Our utils library
var UtilsLibrary = {

    printMessage: function (message)
    {
          console.log("Message: "+message);
    },
	logMessage: function (message)
    {
          console.log("Log: "+message);
    }
}
// Using our library
UtilsLibrary.printMessage("A new message");
UtilsLibrary.logMessage("A new log");

This way we have encapsulated our code in a package like UtilsLibrary object. Besides being more organized, now we can have multiple logMessage functions, in our application, as long as they are in different namespaces.

Thanks for reading. If you found this post useful, you can subscribe to my blog (click at the follow button at the bottom) so you can be notified of new posts.

Advertisements