EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

factory bind #78

Open EdwardZZZ opened 3 years ago

EdwardZZZ commented 3 years ago

class A {
    constructor(readonly name: string) {}

    getName(n: number) {
        console.log(this.name, n);
    }
}

function Factory<T>(clazz: new (...props: any) => T, name: string): T {
    const clzProto = clazz.prototype;

    Reflect.ownKeys(clzProto).forEach((method) => {
        if (method === 'constructor') return;

        const { value, configurable, enumerable } = Reflect.getOwnPropertyDescriptor(clzProto, method);

        if (typeof value !== 'function') return;

        Reflect.defineProperty(clzProto, method, {
            configurable,
            enumerable,
            get() {
                return value.bind(this);
            }
        });
    });

    // TODO
    return Reflect.construct(clazz, [name]);
}

const a = Factory(A, 'aaa');
const { getName } = a;

a.getName(123);
getName(234);