JavaScript: object literal tutorial and example

Object literals in JavaScript are a particular kind of objects. Their main peculiarity is that they cannot be instantiated with the new operator, so that they're a perfect example of the Singleton design pattern. These objects are, in the jQuery's terminology, plain objects. They can be considered as an associative array containing pairs of properties and values or, in a broader sense, structure-like objects, much similar to native C structures. In this post I'm going to guide you in a deep exploration of such objects, also providing some useful examples.

Declaration

Object literals are declared as follows:

var Literal = {};

The above code defines an empty object literal, meaning that it doesn't contain any property. Properties, in turn, are declared as follows:

var Literal = {
  
  property: 'Test',
  method: function() {
    alert(this.property);
  }
};

Each property is followed by a colon, followed by the property's value. Each pair is separated by a comma, except the last one. In our example, this object contains a property and a method. Note that in this case the this keyword points to the current object, thus providing a way to access the object's property by its sole method:

Literal.method(); // alerts 'Test'

OOP features

Our object literal declared above has the following OOP features:

  1. Its constructor property is function Object() ([ native code ]), meaning that it belongs to Object
  2. Its prototype property is undefined, as for other JavaScript objects when they're created the first time
  3. Its prototype property of constructor is [object Object] (see feature 1)

Linking the constructor to another object

Let's declare another object:

function Class() {

  this.prop = 'Foo';

}

We can associate the constructor property of our object literal to this new object as follows:

var Literal = {
  
  property: 'Test',
  method: function() {
    alert(this.property);
  },
  constructor: Class
};

Testing everything out:

alert(Literal.constructor); 
// alerts function Class() {this.prop = 'Foo';}

This is important for internally linking our objects, mainly from an OOP perspective.

Inheritance

Since both Class and Literal have a prototype property which is still without an associated object, we can make the former object access to the latter by linking this property to Literal:

Class.prototype = Literal;

Now Class has access to Literal's properties and methods:

var myClass = new Class();
myClass.method(); // alerts 'Test'

Leave a Reply

Note: Only a member of this blog may post a comment.