JavaScript TRUE inheritance

with No Comments

Hi everyone! This time I want to talk to you about inheritance in JavaScript. I think that most of you know how to implement inheritance in this programming language but do you really sure that you do it the right way? In this article I will show you how some programmers implement inheritance (they do it the WRONG way) and the right way to do it.
In many cases while searching line ‘JavaScript inheritance’ you may find something like this:

Look pretty well. And it seems that it works:

But let me show you why this is a bad approach. I will change the value of field a, then delete it and will try to get its value:

I think this is not the result we want to get. It happens because in JavaScript all properties which are contained in a prototype are shared between all instances of this object without an own property.

One more example:

This is awful. We don’t need this.

We ended up with this result because when we’ve made this:
B.prototype = new A();
we just pushed a link to a new A object with all its properties and methods to the prototype of object B. So that when we try to take inherited property of object B we will always get the value of this property in object A which link is stored in the prototype of object B.

 

To avoid such problems let me introduce the right approach to inheritance in JavaScript. This approach consists of 3 steps:

If you will try to apply previous examples to this approach you will see that now your code works as you expected.

Congratulations! Now you have written TRUE JavaScript inheritance!

 

Useful Links:

The best book about JavaScript I have ever read. – Here you can find complete information about javascript

Leave a Reply