util.ts 626 B

12345678910111213141516171819
  1. export function bindMethods<T extends object>(instance: T): void {
  2. const prototype = Object.getPrototypeOf(instance);
  3. const propertyNames = Object.getOwnPropertyNames(prototype);
  4. propertyNames.forEach((propertyName) => {
  5. const descriptor = Object.getOwnPropertyDescriptor(prototype, propertyName);
  6. const propertyValue = instance[propertyName as keyof T];
  7. if (
  8. typeof propertyValue === 'function' &&
  9. propertyName !== 'constructor' &&
  10. descriptor &&
  11. !descriptor.get &&
  12. !descriptor.set
  13. ) {
  14. instance[propertyName as keyof T] = propertyValue.bind(instance);
  15. }
  16. });
  17. }