Object Oriented JavaScript: Inheritance, (Static) Method

This is a follow-up article of my earlier post on JavaScript class basics. There are some few more things that we actually need to dive into object-oriented programming in JavaScript. Today, In this tutorial, I will try to describe how we can leverage the power of inheritance in JavaScript program. We will also learn, how to declare a normal instance method and as well static method too.

Declaring A Method:

or from outside the main scope, using the prototype keyword, as below:

B.prototype.funcA = function(){
return this.a;
}

Both of the declaration will work in the same way.

JavaScript Inheritance With ‘prototype’:

Besides, generic function/attribute declaration in outside of the original scope, this keyword is also taking care of the responsibilities of the OOP inheritance concept. this keyword is itself an object and all kind of JavaScript class also has this property, regardless we do or do not declare one.

Unlike some-kind of ‘extends’ type of keyword, we will need to use this. Lets see a small code example to get more clear idea about it:

Lets understand what is happening here. As I already said, the ‘prototype’ is itself is an object, we will have to assign an object to it by creating an instance of A class. As soon as we do it, the attributes/methods inside A will also be available inside B, which allows method call like ‘objB.funcA()’ accessible.

Even if we haven’t assigned anything to the ‘prototype’ property of class A, but still it is internally available as an empty object, thus giving the second output.

And sure, as we already assigned something to B class’s prototype, we will get the attributes/methods of A listed here as the third output.

Overriding Existing Method:

It’s very simple like defining a new method. So, lets say, we want to inherit the funcA with a little different implementation so that it returns the value of ‘b’ attribute instead of ‘a’. We can simply write something like follow to achieve that:

B.prototype.funcA = function() {
return this.b;
}

Now it should give you output as value of ‘b’, not ‘a’, if you try with ‘objB.funcA()’ call. Also, same rule apply if you try to override some native existing method. JavaScript is so flexible, isn’t it??

Declaring Static Method:

Well, as you are using JavaScript classes, its natural that at some point you will feel the need of static methods as an object-oriented programmer, such as while trying to implement singleton pattern, adding a static constructor, helper function or factory method etc. Luckily we can achieve that too in JavaScript easily.

Again, there is no ‘static’ keyword here, but you can just assign the function directly instead of using the ‘prototype’ keyword, which causes creating instance method. Here is an example(assuming you have the previously shown code already):