JS: Dive into Classes
Theory: Template method
Late binding leads to one interesting consequence. You can call methods and properties defined in descendants from a base class, even if the descendants themselves may not exist yet. We call late binding “late” because the check only happens when we use the code.
This feature is used in the template method pattern when subclasses have a common logic that relies in part on the behavior of subclasses. We implement this logic in the method from the base class. The part that differs (for each subclass) is delegated to the descendants.
For example, let’s take our tags:
Look at the toString() method. You can see that its code will remain identical for most tags. The only thing that changes is the name of the tag itself:
We can modify the code so that the toString() method moves to the HTMLElement. And the only thing to the subclasses is the tag's name:
The resulting code is better than the original version, as it significantly reduces duplication (the tags are about 100 pieces!). But there's one catch. Tags are always single tags, so the current version of toString() won't work for them. This situation can be resolved in various ways, such as through inheritance.
Create two subclasses for the HTMLElement: one HTMLSingleElement and one HTMLPairElement. Now, specific tags classes must be inherited from one of the specified classes. Each of these classes will have its own implementation of the toString() method.
The resulting code is better than the original version. It significantly reduces duplication (the tags are about 100 pieces!). But there’s one catch. Tags are always single tags, so the current version of toString() won’t work for them. We can resolve the situation in various ways, such as through inheritance.
To resolve this issue, we can create two subclasses for HTMLElement:
- HTMLSingleElement
- HTMLPairElement
We should inherit specific tag classes from one of these specified classes. Each of these classes will have its implementation of the toString() method.
Despite the differences in the toString() implementation, both subclasses require their descendants to implement the same getTagName() method.

