Typescript - 从抽象构造函数调用抽象方法或提供等效功能
Typescript - call abstract method from abstract constructor or provide equivalent functionality
在 Typescript 中 - 不能从抽象构造函数中调用抽象方法(代码可以编译,但会在运行时崩溃)。
以代码崩溃的地方为例:
abstract class Puzzle {
addState = () => {
let data = this.createStateData()
//Perform a operation with data
}
abstract createStateData: () => Object
protected constructor() {
//The code crashes here because createStateData
//has not been defined yet
this.addState()
}
}
class RiverPuzzle extends Puzzle {
createStateData = (): Object => {
return 'Foo'
}
constructor() {
super()
//this.addState()
}
}
在此特定示例中,可以通过取消注释 RiverPuzzle
class 的构造函数中的行并注释抽象 class 的构造函数中的违规行来解决问题.
但是,解决方案不是最优的,因为有许多 class 扩展摘要 class Puzzle
,我不想手动将 this.addState()
添加到每个子class.
的构造函数
什么是更有效的替代方案?
您正在使用 arrow functions as methods,通常不鼓励这样做。它用 this
做一些奇怪的事情,你的 class 的每个实例都有自己的方法,而不是原型上只有一个方法。除非你有充分的理由,否则我建议你使用原型方法(不要使用箭头函数符号),如下所示:
abstract class Puzzle {
addState() {
let data = this.createStateData()
//Perform a operation with data
}
abstract createStateData(): Object
protected constructor() {
this.addState()
}
}
class RiverPuzzle extends Puzzle {
createStateData() {
return 'Foo'
}
constructor() {
super()
}
}
这应该会像您期望的那样发挥更大的作用。
在 Typescript 中 - 不能从抽象构造函数中调用抽象方法(代码可以编译,但会在运行时崩溃)。
以代码崩溃的地方为例:
abstract class Puzzle {
addState = () => {
let data = this.createStateData()
//Perform a operation with data
}
abstract createStateData: () => Object
protected constructor() {
//The code crashes here because createStateData
//has not been defined yet
this.addState()
}
}
class RiverPuzzle extends Puzzle {
createStateData = (): Object => {
return 'Foo'
}
constructor() {
super()
//this.addState()
}
}
在此特定示例中,可以通过取消注释 RiverPuzzle
class 的构造函数中的行并注释抽象 class 的构造函数中的违规行来解决问题.
但是,解决方案不是最优的,因为有许多 class 扩展摘要 class Puzzle
,我不想手动将 this.addState()
添加到每个子class.
什么是更有效的替代方案?
您正在使用 arrow functions as methods,通常不鼓励这样做。它用 this
做一些奇怪的事情,你的 class 的每个实例都有自己的方法,而不是原型上只有一个方法。除非你有充分的理由,否则我建议你使用原型方法(不要使用箭头函数符号),如下所示:
abstract class Puzzle {
addState() {
let data = this.createStateData()
//Perform a operation with data
}
abstract createStateData(): Object
protected constructor() {
this.addState()
}
}
class RiverPuzzle extends Puzzle {
createStateData() {
return 'Foo'
}
constructor() {
super()
}
}
这应该会像您期望的那样发挥更大的作用。