Hello-World
Hello-World

Reputation: 9555

Why does the overridden name property log as undefined

In the following code why does the overridden name property log as undefined?

log::::::::::::::::::::::::::::::::::::::::::

undefinedrunCustomCode
Machines.tsx:19 undefined
Machines.tsx:34 undefinedrunCustomCode
Machines.tsx:19 undefined
Machines.tsx:40 undefinedrunCustomCode
Machines.tsx:19 undefined

code::::::::::::::::::::::::::::::::::::::::::;

interface iMachine {
  name: string
  runCustomCode(): void
  showMachineName(): void
}

abstract class AbstractBase {
  abstract name: string

  abstract runCustomCode(): void

  constructor() {
    this.runCustomCode()
    this.showMachineName()
  }

  showMachineName = () => {
    console.log(this.name)
  }


}

class To extends AbstractBase implements iMachine {
  name: string = 'the to'
  runCustomCode() {
    console.log(this.name + 'runCustomCode')
  }
}
class TV extends AbstractBase implements iMachine {
  name: string = 'the TV'
  runCustomCode() {
    console.log(this.name + 'runCustomCode')
  }
}
class Radio extends AbstractBase implements iMachine {
  name: string = 'the Radio'
  runCustomCode() {
    console.log(this.name + 'runCustomCode')
  }
}





const T = new To()
const TVa = new TV()
const Radioa = new Radio()

console.log([To, TVa, Radioa])

Upvotes: 0

Views: 32

Answers (1)

Przemyslaw Jan Beigert
Przemyslaw Jan Beigert

Reputation: 2486

Reason of undefined instead of this.name is order of executing methods. Constructor of AbstractBase is called before you assign name attribute (name is assigning in To constructor).

----- Edited ----

For sure you have to move this.runCustomCode(); this.showMachineName() from AbstractBase constructor. You can create protected method e.g. protected afterInit and call it into To constructor after super()

Check playground section. In JS code afterInit is called after this.name = '...'

Playground

Upvotes: 1

Related Questions