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

时间:2019-03-09 20:05:00

标签: typescript

在以下代码中,为什么覆盖名称属性记录为未定义?

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])

1 个答案:

答案 0 :(得分:1)

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

-----编辑----

确保您必须将this.runCustomCode(); this.showMachineName()从AbstractBase构造函数中移出。您可以创建受保护的方法,例如保护afterInit并在super()之后将其调用到To构造函数中

检查游乐场部分。在JS代码中,afterInit之后被调用this.name = '...'

Playground