class BaseClass {
    public constructor(protected element: HTMLElement) {}
    public static async build<T extends { new (...args: any[]): {} } = typeof BaseClass>(
        this: T,
        ...args: ConstructorParameters<T>
    ): Promise<InstanceType<T>> {
        const instance = new (this as any)(...args);
        await instance.init();
        return instance;
    }
    protected async init(): Promise<void> {}
}

(async () => {
    // example1
    class Example1 extends BaseClass {}
    const ex1 = await Example1.build(document.body);      // 只需要传递HTMLElement就够了

    // example2
    class Example2 extends BaseClass {
        public constructor(protected element: HTMLElement, private id: number) {
            super(element);
        }
    }
    const ex2 = await Example2.build(document.body, 0);   // 必须传递两个参数,HTMLElement和number
})();
posted on 2019-07-05 15:50  ystrdy  阅读(490)  评论(0编辑  收藏  举报