在以下代码中,为什么覆盖名称属性登录不确定?
在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代码中,afterInit
在this.name = '...'
游乐场