1

I have the following code:

class Base { 

  constructor() {
    console.log(this.table)
  }

  static getAll() { 
    console.log("select * from " + this.table);
  }
}

class User extends Base { 
  static table = 'user'
}
class Room extends Base { 
  static table = 'room'
}

let user = new User()
let room = new Room()

User.getAll()
Room.getAll()

output:

undefined
undefined
select * from user
select * from room

the method getAll works and returns "Select * from User" but, the same field is not accessible, at least I could not on the constructor.

how can I access this static field? thank you

3
  • Base does not have a table property? You probably meant this.table Commented May 10, 2020 at 17:24
  • Sorry, I edit the question :) Commented May 10, 2020 at 17:39
  • 1
    Now you're looking for this.constructor.table. Or, specifically in the constructor, also new.target.table. Commented May 10, 2020 at 21:33

1 Answer 1

0

You cannot use child props from a parent class. If you wish to use some prop in all child classes then add it to a parent class. Otherwise your class hierarchy has wrong architecture. A base class shouldn't know anything about child classes.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, what I want is access the child static field "table" from the Base I'm able to access it on the method getAll() but on the constructor, the line: console.log(this.table) returns undefined alsom I don't want to use User, because I will have multiples tables
I don't want the base class to know nothing from the Child. When I run User.getAll() it invokes the Base method and even in the base Method, it know the current method is from a User and the this.table works but the same does not happen when I'm creating the instance (probably because this in the constructor has another meaning)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.