Skip to main content

Constructor Pattern in JavaScript

Over the last few weeks I've been learning Object-Oriented concepts in JavaScript and have been building applications on top of it. I've an understanding of Object-Oriented concepts in many of the Server side programming languages and was trying to draw parallel lines with JavaScript. As it turns out, JavaScript is a class-less language but the concept of classes can be simulated using functions. In JavaScript, functions are not primitive types but are special kind of objects and hence you can set properties on them and can also invoke methods on them.

Here's a simple JavaScript class:

function Shape(name, sides) {    this.name = name;    this.sides = sides;    this.getInfo = function() { return "Shape name: " + this.name + ", No. of sides = " + this.sides; }; }

In the above class (function) Shape, two properties 'name' and 'sides' have been defined and another property 'getInfo' of type function is also defined. One can create instances of this class by using the new operator (just like other programming languages)

triangle = new Shape("Triangle",3)
square = new Shape("Square",4)

Now both the instances (triangle and square) will have a copy of all three properties of Shape.The 'getInfo' property also gets redefined for all the instances of the Shape. This isn't a good practice and ideally the function should be shared between all the instances of the class. To get around this, the prototype object comes in handy and now my class definition would look like this:

function Shape(name, sides) {    this.name = name;    this.sides = sides; } Shape.prototype.getInfo = function() {    return "Shape name: " + this.name + ", No. of sides = " + this.sides; }
Now the constructor for Shape looks much cleaner and all instances of Shape will be able to call the getInfo function. One thing to note here is that the getInfo property is the part of the Shape object's protoype and not the instance. Although when you loop over the instance of the Shape class (using for..in construct) the getInfo property will be shown as a property of the instance but on calling Object.keys(instance) or instance.hasOwnproperty['getInfo'] would return false. When a property is accessed it is looked in the object and then in the prototype chain.

Inheritance:

The instances 'triangle' and 'square' can be viewed as subclasses of Shape rather than being instances of Shape class. To define a subclass you can define constructor functions for Triangle and Square and mark them as a subclass of Shape class:

function Triangle(name, sides) {   Shape.apply(this, [name,sides]); }
Triangle.prototype = Object.create(Shape.prototype);
Here the constructor for the Triangle is defined which makes call to Shape (super constructor). In the next line, I'm defining Triangle's prototype to be Shape using Object.create() function. If Object.create() is not used then the functions added to Triangle's prototype will be added to Shape's prototype as well and this is not what we want. Now if I create an instance of Triangle, the constructor of Shape would be called instead of Triangle's. This is because constructor property of Triangle (Triangle.prototype.constructor) refers to the Shape's constructor and therefore it needs to updated to refer to its own constructor:

Triangle.prototype.constructor = Triangle

The 'getInfo' function can then be called on the instance of Triangle class:

triangleObj = new Triangle("T1", 3)
triangleObj.getInfo()

Here the definition of getInfo function is searched first in the Triangle object, then in the Triangle's prototype and then in Shape's prototype.

Comments

Popular posts from this blog

File upload and Progress events with HTML5 XmlHttpRequest Level 2

The XmlHttpRequest Level 2 specification adds several enhancements to the XmlHttpRequest object. Last week I had blogged about cross-origin-requests and how it is different from Flash\Silverlight's approach .  With Level 2 specification one can upload the file to the server by passing the file object to the send method. In this post I'll try to explore uploading file using XmlHttpRequest 2 in conjunction with the progress events. I'll also provide a description on the new HTML5 tag -  progress which can be updated while the file is being uploaded to the server. And of course, some ColdFusion code that will show how the file is accepted and stored on the server directory.

Server sent events with HTML5 and ColdFusion

There are several ways to interact with the server apart from the traditional request\response and refresh all protocol. They are polling, long polling, Ajax and Websockets ( pusherapp ). Of all these Ajax and Websockets have been very popular. There is another way to interact with the server such that the server can send notifications to the client using Server Sent Events (SSE) . SSE is a part of HTML5 spec:  http://dev.w3.org/html5/eventsource/

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.