Here is the code where I lose the context when using the spread operator.
Look at function "decorator". Line when I lose context is marked with "ERROR"
/** MethodDecorator example */
class Account {
public firstName: string;
public lastName: string;
public constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
@decorator
public sayMessage(msg: string): string {
return `${this.firstName} ${this.lastName}: ${msg}`
}
}
function decorator(target: any, key: string, desc: any): any {
let originDesc = desc.value;
desc.value = function(...args: any[]): any {
return originDesc(...args); // ==> ERROR: context lost
//return originDesc.apply(this, arguments); // ==> all OK
};
return desc;
}
let persone = new Account('John', 'Smith');
let message = persone.sayMessage('Hello world!');
console.log(message); // ==> undefined undefined: Hello world!
As far as I understand originDesc(...args);
equals originDesc.apply(this, arguments);
so why is my context lost?