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

How to use the APP_INITIALIZER token to hook into the Angular bootstrap process

I've been building applications using Angular as a framework of choice for more than a year and this post is not about another React vs Angular or the quirks of each framework. Honestly, I like Angular and every day I discover something new which makes development easier and makes me look like a guy who built something very complex in a matter of hours which would've taken a long time to put the correct architecture in place if I had chosen a different framework. The first thing that I learned in Angular is the use of the APP_INITIALIZER token.

Using MobX to manage application state in a React application

I have been writing applications using React and Redux for quite some time now and thought of trying other state management solutions out there. It's not that I have faced any issues with Redux; however, I wanted to explore other approaches to state management. I recently came across MobX  and thought of giving it a try. The library uses the premise of  `Observables` to tie the application state with the view layer (React). It's also an implementation of the Flux pattern wherein it uses multiple stores to save the application state; each store referring to a particular entity. Redux, on the other hand, uses a single store with top-level state variables referring to various entities.

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...