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

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.

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools  some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code. What is Minification? Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript f

On GraphQL and building an application using React Apollo

When I visualize building an application, I would think of using React and Redux on the front-end which talks to a set of RESTful services built with Node and Hapi (or Express). However, over a period of time, I've realized that this approach does not scale well when you add new features to the front-end. For example, consider a page that displays user information along with courses that a user has enrolled in. At a later point, you decide to add a section that displays popular book titles that one can view and purchase. If every entity is considered as a microservice then to get data from three different microservices would require three http  requests to be sent by the front-end app. The performance of the app would degrade with the increase in the number of http requests. I read about GraphQL and knew that it is an ideal way of building an app and I need not look forward to anything else. The GraphQL layer can be viewed as a facade which sits on top of your RESTful services o