JavaScript: object literals and inheritance

An object literal is a peculiar form of JavaScript object that cannot be instantiated using the new operator. In practice, this kind of object works as a singleton. However, sometimes it's preferable to use this object to handle inheritance. In JavaScript, only objects which belong to the Function constructor type can be instantiated using the new operator. Instead, object literals have Object (native code) as their constructor. Attempting to redefine this behavior using the constructor property produces no results. So here's a solution:

var Literal = function(){};

var Class = {

  property: 'Test',
  method: function() {
    alert(this.property + ' method');
  }



};

Literal.prototype = Class;

First, we create an empty object using the Function constructor type. Then we create a normal object literal. Finally, we link together these two objects using the prototype property of the first object by making it point to the object literal. In this case, all the properties and methods of the first object can actually be defined in the object literal. A simple test:

window.onload = function() {

  var literal = new Literal();


  alert(literal.property); // alerts 'Test'
  literal.method();  // alerts 'Test method'


};

As you can see, now the prototype property of the first object has been entirely rewritten using the object literal.

Leave a Reply

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