Monday, August 27, 2018

Javascript Inheritance

Intro

Inheritance in Javascript is bad! Everybody who has ever used Javascript knows that. The concept of "method inheritance" and prototypes could be even hard to grasp for someone who is used to more modern languages like Java. It was hard for me as well. But what if you really need to develop a small hierarchy in Javascript? Of course, there are some alternatives like GTW or Typescript with better support for classes and inheritance. But what if your boss just likes Javascript or the customer doesn't want to hear about any modern replacements? And Javascript has a lot of frameworks and libraries. Actually there are approaches to making a small hierarchy possible.

Abstract Factory Approach

Here is what we need to accomplish:

We cannot declare these properties on the functions and then write
BaseObject.prototype = new VeryBaseObject();
ConcreteObject.prototype = new BaseObject();
because modifying any of the maps from BaseObject or VeryBaseObject will change the maps for all descendants.

Solution

We are going to use a factory to create objects. It won't be an abstract factory just a factory. And use the reference to the actual object to set the properties on the object itself. We add some init functions that will create our properties:

Then in the factory we'll call these methods from the ConcreteObject like this:
switch(objectType) {
    case OBJECT_TYPE_CONCRETE1:
        obj = Object.create(new ConcreteObject1()); 
        break;
    ...
}
obj.initvbo();
obj.initbo();
obj.initCustom();

If the function is called from the ConcreteObject instance this will be that instance. And we'll have the necessary properties installed on the instance without affecting the prototype. 
Here is the object structure that we'll get:
With the properties on the ConcreteObject instance we can get a Java-like inheritance on Javascript. 

In fact it could be a bit more complicated than that if different functions need to be called for different object types. Then the method that creates the object must be modified to call the appropriate functions. 

This simple solution may help if it is REALLY necessary to create and use a Java-like object hierarchy in Javascript. 

No comments:

Post a Comment