Register to get access to free programming courses with interactive exercises

Inheritance JS: Dive into Classes

Class inheritance is a mechanism that allows you to create classes (called subclasses) based on other classes (called base or superclasses). In this case, subclasses inherit the structure of the base classes, i.e., they get to use everything that was defined in the base classes.

Inheritance is a very complex system. Therefore, it'll be studied in several stages, throughout the course. Also, don't forget that when we're talking about classes in JavaScript, we're really talking about prototypes.

Let's take the HTML structure as an example to look at inheritance. Each tag in HTML is unique in its own way. On the other hand, they all share common attributes and some other characteristics. Let's try to represent this using class hierarchy.

// Base class for all tags. It knows how to work with attributes.
class HTMLElement {
  constructor(attributes = {}) {
    this.attributes = attributes;
  }

  setAttribute(key, value) {
    this.attributes[key] = value;
  }

  getAttribute(key) {
    return this.attributes[key];
  }

  getTextContent() {
    return this.body;
  }

  setTextContent(body) {
    this.body = body;
  }

  stringifyAttributes() {
    // build: key="value" key2="value2"
  }
}

Specific elements represented by tags in HTML inherit this class:

// Anchor is a link. The HTMLAnchorElement class defines the tag “a”.
// Inheritance is done using the keyword “extend”
class HTMLAnchorElement extends HTMLElement {
  toString() {
    // Parent method
    const attrLine = this.stringifyAttributes();
    // Parent method
    const body = this.getTextContent();
    return `<a${attrLine}>${body}</a>`;
  }
}

Inheritance is written as follows A extends B. This entry means that A inherits B. Now let's see how inheritance works:

// The parent constructor
const anchor = new HTMLAnchorElement({ href: 'https://ru.hexlet.io' });
anchor.setTextContent('Hexlet');
console.log(`Anchor: ${anchor}`); // toString() is called automatically
// => Anchor: <a href="https://hexlet.io">Hexlet</a>

There is no constructor definition inside HTMLAnchorElement, but thanks to inheritance, this class has access to all the properties of the superclass. JavaScript calls them automatically when you access them. In turn, methods that are inside toString() that are not in the current classes, and therefore are also taken from the parent class, are called.

Chain of Inheritance

Unlike interfaces, JavaScript has single class inheritance. In other words, only one class can be inherited. Just like in Java. Multiple inheritance was removed from these languages on purpose, because of its high complexity and the problems it adds (e.g., method and property collisions). On the other hand, the chain of inheritance itself can be as deep as you like:

class D {}
class C extends D {}
class B extends C {}
class A extends B {}

Type check operator

The instanceof operator takes into account classes from the prototype inheritance chain:

const anchor = new HTMLAnchorElement();
if (anchor instanceof HTMLElement) {
    console.log('!!!');
}
// => !!!

Don't forget that such checks mean you can't use polymorphism. Sometimes you can't do without them, but in the vast majority of cases it's better to be bound to the object interface.


Recommended materials

  1. Inheritance (Wiki)

Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.