It was brought to my attention that the issue I encountered was due to the use of GraphQL resolvers in running my decorated method. This resulted in the scope of this
being undefined
. Nevertheless, the core of the question provides valuable insights for anyone facing challenges with decorators.
Here is a simplified version of the decorator I intend to use:
const someDecorator = (argPassed: any) => {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value;
// Perform operations here...
console.log(argPassed);
// Wrapping the original method
descriptor.value = (...args: any[]) => {
const result = originalMethod.apply(this, args);
return result;
};
};
};
I've utilized arrow functions within the decorator as it was necessary to ensure a certain scope is maintained, albeit different from a typical this
scope.
Below is an example of the class where I'm utilizing the decorator on a specific method:
class SomeClass {
constructor() {
}
@someDecorator('Passing this in...')
public doingSomething(argPassed: string) {
console.log(this); // Outputs: { default: SomeClass { otherMethodInMyClass: [Function] } }
// Unfortunately, I can't do this
// this.otherMethodInMyClass is not a function
this.otherMethodInMyClass(argPassed);
}
private otherMethodInMyClass = (argPassed: any) => {
// Implement functionality...
}
}
Currently, when using the decorator, the scope returned by doingSomething
is:
{ default: SomeClass { otherMethodInMyClass: [Function] } }
In contrast, without the decorator, I get:
SomeClass { doingSomething: [Function], otherMethodInMyClass: [Function] }
Is this expected behavior? If not, what might be going wrong? If it is normal, how can I enable my method to utilize its own scope since I need to call other methods thereafter?
Update:
As correctly pointed out by @jcalz, an arrow function does not have its own this
context. However, when I employed a non-arrow function throughout the decorator, this
ended up being undefined
.
Thank you in advance