Parent and child constructors
if I have a UserForm class:
and a View class:
Does anyone know why
new UserForm('root')
causes the UserForm class to inherit the View constructor and set the parentElement
variable correctly? Definitely wasn't the behavior I was expecting 🤔
My best guess is that behind the scenes UserForm
is creating a new object from the View
's prototype, and because one isn't present in the UserForm
class it inherits it rather than overriding it if it had been explicitly provided - that would also explain why I don't have to call super
in this case to set View properties? This is all a guess though, it's been a while since I've looked at prototype inheritance, and this seems like a bit of an edge case that's not included often5 Replies
Your guess is pretty much correct
when creating a class which inherits from some other class, you can choose to give the child it's own constructor, where you must call
super()
at some point (and also must call it before using this.
)
Or, you can choose that the child class doesn't need it's own constructor, in which case you can imagine that the "default constructor" is simply constructor() { super(); }
.
Of course, it's a little bit more than that as it does some stuff with prototypes, but in terms of behavior;
if a child class is not given a constructor, it will automatically inherit it's parent's constructor.what about classes who don't have a parent and don't have a constructor, for example; In their case the parent (and by extension, their constructor) is just
Object
, which all classes inherit from automagically.This is I guess where my confusion came in - if omitted I expected it to have a default constructor like you've described, but it seems to be inheriting the parent's constructor rather than getting a default - because that default wouldn't pass the child's arguments to
super()
, and yet that seems to be happening?
I've just thought that this might actually be TS behaviour as that's what I've been looking at...this is all vanilla JS stuff, you're right that it inherits the constructor rather than a default of calling
super()
- I just find the default thing an easier way of visualising it, even though it's not technically correctah ok cool, just wanted to double check that was what was happening, thanks for the help!
np!