Parent and child constructors

if I have a UserForm class:
class UserForm extends View {
// no constructor
}
class UserForm extends View {
// no constructor
}
and a View class:
class View {
constructor(parentElement){ this.parentElement = parentElement }
}
class View {
constructor(parentElement){ this.parentElement = parentElement }
}
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 often
5 Replies
WillsterJohnson
WillsterJohnson•15mo ago
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;
class MyClass {
helloWorld() {
return "Hello, world!";
}
}
class MyClass {
helloWorld() {
return "Hello, world!";
}
}
In their case the parent (and by extension, their constructor) is just Object, which all classes inherit from automagically.
JWode
JWode•15mo ago
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...
WillsterJohnson
WillsterJohnson•15mo ago
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 correct
JWode
JWode•15mo ago
ah ok cool, just wanted to double check that was what was happening, thanks for the help!
WillsterJohnson
WillsterJohnson•15mo ago
np!