JavaScript – Some code for inheritance in JavaScript

The last month I am writing mainly small pieces of code for JavaScript, because I think I start to like the language somehow (and I took 3 books for review in JS and so far I have only reviewed one). 🙂

Thus, today I will show how to make inheritance in JS. Not science fiction or rocket engineering, but still rather complicated (and unfortunately more advanced than the inheritance in VBA). In the code below we have two objects of type article and type JavaScriptArticle. They both use the method information, which is a method of the object article. However, because of inheritance, they share the method like good friends. This is the result:

js_inheritance

This is the code:

However, if you wish to become a little fancier, you may declare the method in the main object. Or with other words, you may declare the method (or function ) information in the object Article. And thus make something rather more complicated to understand for a new comer, but easier to maintain. Like this (pay attention to the method information and the new lines in the object Article:

Last but not least (actually least), I want to present a nice way of creating an object with constructor in JS. I have already had some similar articles, but this one is probably also needed. Here comes the code:

As you can imagine, this is the result in the console from the code:

js_inheritance

The code is here in GitHub. Also of the previous example.

That’s all folks! Enjoy the new 2016! 🙂 😀

About

A VBA Developer.

Tagged with: ,