How to avoid hard coded this? in Decorators
Don't use an arrow function. Use a function expression:
function log(target: Object, key: string, value: any) { return { value: function(...args: any[]) { var a = args.map(a => JSON.stringify(a)).join(); var result = value.value.apply(this, args); var r = JSON.stringify(result); console.log(`Call: ${key}(${a}) => ${r}`); return result; } };}
That way it will use the function's this
context instead of the value of this
when log is called.
By the way, I would recommend editing the descriptor/value parameter and return that instead of overwriting it by returning a new descriptor. That way you keep the properties currently in the descriptor and won't overwrite what another decorator might have done to the descriptor:
function log(target: Object, key: string, descriptor: TypedPropertyDescriptor<any>) { var originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { var a = args.map(a => JSON.stringify(a)).join(); var result = originalMethod.apply(this, args); var r = JSON.stringify(result); console.log(`Call: ${key}(${a}) => ${r}`); return result; }; return descriptor;}
More details in this answer - See the "Bad vs Good" example under "Example - Without Arguments > Notes"
I believe you can use
var self = this;
in order to preserve the 'this' at that specific point. Then, just use self
at the later point where you would have wanted that particular this