Register to get access to free programming courses with interactive exercises

Overriding Methods JS: Dive into Classes

Eliminating code duplication is not the only thing to use class inheritance. Sometimes, we can use it to change the existing behavior of a base class.

The <select> tag in the DOM is represented by the HTMLSelectElement class. It has additional methods needed to work with the list of elements. One such method is item(index). You can use it to retrieve a specific option from the list:

<form>
  <select name="variants">
    <option>Opt 1</option>
    <option>Opt 2</option>
    <option>Opt 3</option>
  </select>
</form>
// Hypothetical code that returns the form above as an element HTMLSelectElement
const element = document.querySelector('select');

element.item(0); // HTMLOptionElement(textContent="Opt 1")
element.item(1); // HTMLOptionElement(textContent="Opt 2")

Let's imagine that we frequently need to access the elements of this list from the end. You would have to execute this kind of code all the time:

// The length property describes the number of option elements inside select
element.item(element.length - 1);

There's nothing criminal about this code, but it could be better. One possible solution to this problem is to extend the method's behavior and teach it to work with negative numbers. The ability to refer to indexes in reverse order is a common practice in many languages:

// Last element
element.item(-1); // HTMLOptionElement(textContent="Opt 3")
// Third from the end
element.item(-3); // HTMLOptionElement(textContent="Opt 1")

How do you do that? Inheritance makes it possible to override superclass methods. Take a look at this example:

class HTMLCustomSelectElement extends HTMLSelectElement {
  item(possibleIndex) {
    const realIndex = possibleIndex >= 0 ? possibleIndex : this.length + possibleIndex;
    // Superclass points to the parent class
    return super.item(realIndex);
  }
}

The HTMLCustomSelectElement subclass created above overrides the item(index) method. Overriding means a subclass creates a method with the same name as the parent class.

Our new method does the extra work of calculating the index but still needs the original item(index) method to select the desired item.

To do so, we use a special syntax that specifies explicitly that we shpuld take the method from the parent class: super.item(realIndex).

Why did we need to use special syntax? Imagine if it had this code instead:

item(possibleIndex) {
  this.item(possibleIndex);
}

Which item() method should we take in this case — the one we're in right now or the parent one? Inheritance always chooses the method closest to the inheritance chain. So, a call through this will generate recursion, but the parent method will never be called.

For the same reason, it's not possible to call methods that are overridden in the descendants outside the object:

const select = new HTMLCustomSelectElement();

// This call always refers to the item method overridden inside  HTMLCustomSelectElement
// It's not possible to call item directly from  HTMLSelectElement
select.item(3);

Overriding is not limited to one level of inheritance. We can override any overridden method again in the descendants of the current class.

Calling the parent class constructor works a little differently. To do this, use super as a function:

class MyClass extends BaseClass {
  constructor(param) {
    super(param);
  }
}

Using descendants

Creating a descendant class and starting to use it are two differences.

In situations where we create these classes, everything is simple. We replace the calls of the old class with the new one.

But if someone else created the objects of this class by their code, the task becomes more complicated. To substitute such a class, you need support for polymorphic behavior from the other person's code.

For example, when working with the DOM, objects of these classes are sometimes generated by the programmer or the system. For example:

// Making it yourself
const element1 = new HTMLSelectElement();

// An HTMLSelectElement object is created somewhere inside
const element2 = document.querySelector('select');

Can we replace the class in the querySelector() example? It depends on the implementation of the DOM library. It isn't possible in the libraries that we know of. It means that the only way to use your class is to convert the returned object into a class object we want. Is it worth it? Almost certainly not:

const element = document.querySelector('select');
const convertedElement = new MyHTMLSelectElement(element);

In other words, inheritance to redefine behavior, while seemingly a logical step, has some usage limitations.


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
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

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.