I am aware that in many languages inheriting from a class that has only private constructors is simply not possible, because the subclass needs to call the superclass constructors (e.g. in Java -- well, at least when neglecting the counter-example of the accepted answer of the link).
Private constructors are not supported directly in JavaScript, but there is a common pattern for how to simulate them. (see also this SO-question on private constructors in JavaScript). So for classes with such private constructors I was expecting the same constraint, i.e. not being able to inherit from the class. I have a particular example in mind, namely the HTMLVideoElement
. This class throws Illegal constructor
exceptions, if one tries to construct it via new HTMLVideoElement()
(at least with recent Firefox (105) and Chrome (106) browsers). I don't know the native code behind this class, but this looks to me exactly like a class with private constructors in the sense I mentioned. However, if I build a simple subclass
class MyVideo extends HTMLVideoElement {
constructor() {
super();
}
}
then I can create an instance of this subclass via new MyVideo()
without getting any exception. On the one side I'm happy about this, but on the other side I'm suspicious that if I rely on this behaviour, it might later be changed by the browsers (as strictly speaking there are no private constructors yet in the language, I guess there are no specs yet how they should behave). So my own test with the above subclass suggests that the answer to my question is in fact 'yes', while I think that it actually should be 'no'. Does anybody have more insight into this? Is it wanted behavior? Can I rely on it for the future?
Edit: For people who want to reproduce my claim that I can call new MyVideo()
without getting an exception, I have to add the observation that this is only true if I previously assigned the class to a custom element via customElements.define('my-video', MyVideo, { extends: "video"})
. If I omit this step and try to call the constructor, I do get the exception (again tested in Firefox and Chrome). Sorry for the initially misleading description, but I realized this subtle difference only now.