Matthias Thaler
Matthias Thaler

Reputation: 41

Access properties from derived class

abstract class Base {
  constructor() {
    console.log(this.components)
  }
  components = ['']
}
class Child extends Base {
  components = ['button', 'text']
}

const f = new Child()

Running this code, I get

[''] 

But I would rather like to get

['button', 'text']

from the derived Class. Reason I want to do this: I want to validate the "components"-property, which the user defined in the Child. Is it not possible ?

Upvotes: 0

Views: 51

Answers (2)

Sam Denty
Sam Denty

Reputation: 4085

The components property is being set just after the constructor in the base class has been called:

abstract class Base {
  constructor() {
    console.log(this.components)
  }

  components = ['']
}

class Child extends Base {
  constructor() {
    // inherited components from base = ['']
    super() // Call base constructor

    // this.components = ['button', 'text']
  }

  components = ['button', 'text']
}

const f = new Child()

You need to wait for the base constructor to synchronously complete, before you can access the new values - ie. by using setTimeout:

constructor() {
  setTimeout(() => console.log(this.components))
}

Ideally you should pass the components as parameters:

abstract class Base {
  constructor(public components = ['']) {
    console.log(components)
  }
}

class Child extends Base {
  constructor() {
    super(['button', 'text'])
    // this.components = ['button', 'text']
  }
}

const f = new Child()

Upvotes: 1

Mostafa Sayed
Mostafa Sayed

Reputation: 256

try this:

abstract class Base {
  constructor(components) {
    console.log(components)
  }
}
class Child extends Base {
  constructor() {
    super(['button', 'text'])
  }
}

const f = new Child()

or

abstract class Base {
  constructor(components) {
    console.log(components)
  }
}
class Child extends Base {

}

const f = new Child(['button', 'text'])

Upvotes: 1

Related Questions