为什么覆盖属性属性记录为未定义



在以下代码中,为什么覆盖名称属性登录不确定?

undefinedrunCustomCode
Machines.tsx:19 undefined
Machines.tsx:34 undefinedrunCustomCode
Machines.tsx:19 undefined
Machines.tsx:40 undefinedrunCustomCode
Machines.tsx:19 undefined
态>
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])

未定义的原因而不是this.name是执行方法的顺序。在分配name属性之前,请调用AbstractBase的构造函数(在To构造函数中分配名称)。

-----编辑----

确保您必须从Abstractbase构造器移动this.runCustomCode(); this.showMachineName()。您可以创建受保护的方法,例如受保护inafterInit,并在超级()

之后将其调用为构造函数

检查操场部分。在JS代码中,afterInitthis.name = '...'

之后调用

游乐场

最新更新