Sorry if this is bizarre or anti-pattern.
Suppose I have a static method on a child class, e.g (heavily simplified for readability)
class User extends Model {
//...
static getAll(){
db.execute('SELECT * FROM users');
}
}
Since I have multiple models I might want a getAll method on, it seems ideal to define getAll on the Model class, which makes reference to a tableName class variable. Ideally it would look something like
class Model {
static getAll(){
db.execute(`SELECT * FROM ${this.tableName}`);
}
}
//...
User.tableName = 'users';
This won't work, because ES6 doesn't like you defining class variables like that. There are a number of workarounds, such as adding a tableName parameter in the parent then applying users to it in User:
class Model {
static getAll(tableName) {
db.execute(`SELECT * FROM ${tableName}`)
}
}
//...
class User extends Model{
static getAll() {
Model.getAll('users')
}
}
but explicitly re-writing inherited functions for all of a class's children like this seems dreadfully anti-pattern. Other solutions I've seen (such as using static functions to return constants, or wrapping both classes in an object) are kinda ugly and not a pattern I want to commit to unless I have to. So I'm looking for an easily-readable ES6 pattern that lets me do the following:
- Inherit static methods from a parent class.
- Refer to class variables (or something equivalent) in the parent class, such that they can be specified for different child classes
- Not have to explicitly refer to inherited methods in the child class.
Does such a solution exist, or is it worth doing it the 'hard way' in ES5?
Model.getAllas opposed toUser.getAll, right? If that's the case, I can't think of a way this is doable w/o a hackModel'sgetAllmethod without having to redefine it onUser. Fairly sure this is directly doable in Ruby and other OOPLs. Is there maybe some other way of effectively doing the same thing while keeping my DRY? Perhaps without ES6 class inheritance?