在以下代码中,为什么覆盖名称属性记录为未定义?
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])
答案 0 :(得分:1)
未定义而不是this.name
的原因是执行方法的顺序。在分配AbstractBase
属性之前,将调用name
的构造函数(名称是在To
构造函数中分配的。)
-----编辑----
确保您必须将this.runCustomCode(); this.showMachineName()
从AbstractBase构造函数中移出。您可以创建受保护的方法,例如保护afterInit并在super()之后将其调用到To构造函数中
检查游乐场部分。在JS代码中,afterInit
之后被调用this.name = '...'