我正在尝试创建一个类的实例,但由于某种原因,构造函数没有运行。
首先我在这里定义类,然后将它传递给Server
这样的新实例(有效):
class MyMatchMaker extends MatchMaker {
public autoStartClientCount: 2
}
new Server({
matchMaker: MyMatchMaker
})
接下来,我接受传入的选项,并将默认值与用户定义的选项(工作)合并。然后我调用new this.settings.matchMaker(this)
它会运行,并创建一个MyMatchMaker
的新实例。
export interface MatchMakerType<T extends MatchMaker> {
new(server: Server): MatchMaker
}
export interface Options {
matchMaker: MatchMakerType<MatchMaker>
}
export class Server {
private readonly matchMaker!: MatchMaker
public readonly settings: Options
public readonly ps: Partial<Options> = {
matchMaker: undefined
}
public constructor(options: Options) {
this.settings = Object.assign(this.ps, options) as Options
this.matchMaker = new this.settings.matchMaker(this)
console.log(this.matchMaker)
}
}
创建了一个新实例,但是,此类的构造函数不会运行,也不会创建WaitList
的新实例。
export abstract class MatchMaker {
public waitList: WaitList = new WaitList
public constructor(server: Server) {
console.log('match maker')
}
}
是什么导致这种情况发生?
当我转储this.matchMaker
时,我在节点控制台中得到了这个(这包括我从上面修剪过的设置):
MyMatchMaker {
server:
Server {
clients: [],
ps:
{ port: 5555,
workers: -1,
game: 'C:\\Users\\rnaddy\\Documents\\vscode\\projects\\red5-test\\build\\TickTacToe.js',
type: 'websocket',
redis: undefined,
matchMaker: [Function: MyMatchMaker] },
settings:
{ port: 5555,
workers: -1,
game: 'C:\\Users\\rnaddy\\Documents\\vscode\\projects\\red5-test\\build\\TickTacToe.js',
type: 'websocket',
redis: undefined,
matchMaker: [Function: MyMatchMaker] },
matchMaker: [Circular] },
game: 'C:\\Users\\rnaddy\\Documents\\vscode\\projects\\red5-test\\build\\TickTacToe.js',
autoStartClientCount: 2 }