I have a base class and another that extends it, how can I access fields in the constructor?
class BaseModel {
constructor() {
console.log('no fields :(')
console.log(this.fields)
this.fields.map((field) => {
field.label = field.label || field.name;
})
}
}
class UserModel extends BaseModel {
fields = [
{ name: 'id' },
{ name: 'name' },
{ name: 'email' },
];
constructor(name, email) {
super();
this.name = name;
this.email = email;
}
}
const user = new UserModel('bob', '[email protected]');
console.log(user);
I went about 2 pages deep and didn’t find a satisfactory answer of how to set this up. The best I found was to set a timeout in the constructor which seemed wrong.
2
Answers
I messed with this for a bit longer and came up with a pretty reasonable solution. Feels like the least best of a bunch of not so great options.
If you just rename the constructor on BaseModel to
init()
, then callsuper().init()
in the child class it works fine, same w/ models 2-deep, could use more testing but seems like a decent solve for now.If you want to access
fields
in the parent constructor sync you should pass the fields to it: