Inheritance lets a child class reuse functionality from a parent class and add or customize behavior. It helps explain how familiar HTML elements relate to HTMLElement and how components can share common functionality. section 2.1 section 4.5
Inheritance appears in several forms in web development:
- In object-oriented programming, a class such as Mammal extends Animal and receives its functionality without redefining it. section 2.1
- DOM elements have specific classes derived from HTMLElement; inheritance helps explain why elements such as divs and buttons have their own constructors. section 2.1
- A component can extend a shared base class. For example, a visual countdown component inherits frame-update behavior and can override update; calling super.update() continues the base behavior. section 4.5
- CSS custom properties also inherit: a value on a broader scope can apply to a child, while a more specific value can take precedence. These properties can cross a Shadow DOM boundary. section 10.2
Listing 4.10. Creating an inheritable base for components to update every frame
<html>
<head>
<script>
class GameComponentBase
extends HTMLElement { #1
constructor() {
super();
this.onUpdate();
}
update() {} #2
onUpdate() { #3
this.update();
requestAnimationFrame( () => this.onUpdate());
}
}
class VisualCountdownTimer
extends GameComponentBase { #4
connectedCallback() {
this.timer = 200;
this.style.backgroundColor = 'green';
this.style.display = 'inline-block';
this.style.height = '50px';
}
update() {
this.timer --;
if (this.timer <= 0) {
this.timer = 200;
}
this.style.width = this.timer + 'px';
}
}
customElements.define('countdown-timer', VisualCountdownTimer);
</script>
</head>
<body>
<countdown-timer></countdown-timer>
</body>
</html>
See a base component that extends HTMLElement and a countdown component that extends the base class to reuse frame-update behavior. section 4.5


















