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 that class inheritance is used for. Sometimes, it's used 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 that are 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 behavior of the method 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;
    // super points to the parent class
    return super.item(realIndex);
  }
}

The HTMLCustomSelectElement subclass created above overrides the item(index) method. Overriding means that 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 it still needs the original item(index) method to select the desired item. To do this, a special syntax is used that specifies explicitly that the method must be taken 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? The way inheritance works is that the method closest in the inheritance chain is always chosen. 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 have been 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. Any overridden method can be overridden again in the descendants of the current class.

Calling the parent class constructor works a little differently. To do this, just 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 big differences. In situations where these classes are created by you, everything is simple - just replace the calls of the old class with the new one, but if the objects of this class are created by someone else's code, then 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 themselves and sometimes by the system. For example:

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

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

Can you replace the class in the querySelector() example? It depends on the implementation of the DOM library. This isn't possible in the libraries that I know of. This means that the only way to use your own class is to convert the object that's returned into an object of the class 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, actually has serious usage limitations.


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.