Mike Manfrin
Mike Manfrin

Reputation: 2762

Is it possible to access an attribute of a child class from the parent class?

I have a parent class where I am defining store-relation function, and a child class which defines its table on the store. In the parent class, I'm defining a save() function which connects to the instance's table, but the table is defined on the child. I figured I could just set the constructor of the parent to accept the child's tableName, but my linter is complaining that super must be called before I reference this (even though I want to pass an attribute on this up to super).

Here's the parent:

export class StoredObject {
    constructor(private tableName: string) {}

    public save() {
        store.collection(this.tableName) //...
    }
}

And the child:

export class Inventory extends StoredObject {
    tableName = "inventory";

    constructor(
        public myVar //...
    ) {
        super(this.tableName)
    }
}

I know one solution is to make a getter function that simply returns the value of this.tableName, but that seems hackish. I also know that I could simply put the actual string in super (e.g., in Inventory, have the constructor be { super("inventory") }, but that seems inelegant. I get the suspicion there is a way of conventionally achieving what I'm trying to do, but I can't seem to find it.

Upvotes: 2

Views: 1481

Answers (1)

Paarth
Paarth

Reputation: 10377

Take a look at Ryan Cavanaugh's response here

Specifically,

The order of initialization is:

  1. The base class initialized properties are initialized
  2. The base class constructor runs
  3. The derived class initialized properties are initialized
  4. The derived class constructor runs

You've made your super class responsible for initializing the tableName property and it must be able to do that before your subclass can be created. You'll either have to pass in "inventory" or alter this relationship.

Upvotes: 4

Related Questions