I've always been fascinated by web components, but there's one thing I keep wondering about. When I define a component like this: `class hedgehog extends HTMLElement`, it clearly indicates what I'm extending. And I know that using `super()` is a requirement, which ensures that it's always there. Plus, `super()` has to be the first line of the constructor, giving us a consistent structure. So, if all that is true, why do I have to explicitly call `super()`? Shouldn't it be automatically handled by the API?
4 Answers
Some constructors may require parameters, and since we can't know in advance what those parameters will be, it can't be automatically managed. You actively need to specify what you want to pass to it.
`super()` is used to call the parent constructor, and it needs to be called before you can use `this`. Although it doesn't have to be the very first line, it has to be called early enough to avoid issues.
That's a great point! Web components rely on standard JavaScript classes, and the language's design expects you to explicitly call the super constructor, which is integral to how inheritance works.
It's important to remember that this is JavaScript, not a unique language just for components. The design aligns with general OOP principles found in JavaScript and other languages, so the `super()` call is necessary.
Exactly! For example, if you have a class like `Dog extends Animal`, you might want to pass parameters like `name` when calling the parent constructor: `super(name)`. That way, you can properly initialize things in your subclass.