Decorator to call a method before any other messes with “this” context

You’re almost there. You’re getting undefined because this in your decorator is undefined and should be referring to an instantiated instance of your target. Changing that definition to a regular function call instead of an arrow function should do the trick.

export const ensureCall = (method: string) => {
  return (target: any) => {
    for (const prop of Object.getOwnPropertyNames(target.prototype)) {
      if (prop === method || prop === 'constructor') continue;

      const originalMethod = target.prototype[prop];
      if (originalMethod instanceof Function) {
        // Regular function declaration
        target.prototype[prop] = async function(...args: any[]) {
          await target.prototype[method]();
          // Now `this` refers to an instantiated instance
          return originalMethod.apply(this, args);
        };
      }
    }
  };
};

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top