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

Custom validation messages for HTML5 Input elements using the constraint validation API

HTML5 has introduced several input types such as EMAIL, URL, RANGE, SEARCH, DATE, TIME, etc,. Most of the modern browsers have implemented them and are ready to be used in a HTML document. Another exciting feature introduced in HTML5 is the form validation. Instead of writing JavaScript to validate users input, browsers can now validate it and show an appropriate message if the validation fails. The validation message is shown in line with the field for which the validation has failed. The default error message is shown when the validation fails. In this post I'll explain how these error messages can be changed.

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.

A cheat sheet of keyboard shortcuts in ColdFusion Builder

In my last post I have explained about keyboard shortcuts in ColdFusion Builder 2.0. This blog post contains a list of all shortcut keys and I have listed these keyboard shortcuts based on the categories that it falls into. Well, this post was not planned since users can easily get to know the keyboard shortcuts by navigating to the preferences (ColdFusion -> Profiles -> Keys). However, I met Joshua at Scotch on the rocks in Edinburgh and he suggested that it would be nice to have the list of keyboard shortcuts handy. So this post is for those who would like to have the list with them and refer it whenever required.


Keyboard shortcuts for inserting text:

These are the keyboard shortcuts which are used to insert some text into the editor:

CommandKeyboard shortcuts on WindowsKeyboard shortcuts on MacInsert anchor tagCTRL + T, LCMD + T, LInsert bold tagCTRL + T, BCMD + T, BInsert br tagCTRL + T, RCMD + T, RInsert cfabortCTRL + T, ACMD + T, AInsert cfdumpCTRL + T, DCMD + T, DInsert cfs…