我有一个带有函数类型实参的Typescript方法装饰器。我将该函数定义为箭头函数,但是我失去了this
的上下文。我需要帮助来理解下面的第一个代码段为什么不起作用。这是示例代码。链接到stackblitz
function gamora(a: () => string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args) {
this.name = a();
return originalMethod.apply(this, args);
}
return descriptor;
}
}
class MyClass {
name = 'default';
gamora = 'Gamora';
@gamora(() => !!this && !!this.gamora ? this.gamora : 'nada')
test1() {
return `${this.name}!`;
}
}
const my = new MyClass();
const test1Val = my.test1();
console.log('First', test1Val); // it prints nada
由于必须从该装饰器参数函数访问该类的属性,因此必须采用以下解决方案。
function carol(a: () => string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args) {
this.name = a.call(this);
return originalMethod.apply(this, args);
}
return descriptor;
}
}
class MyClass {
name = 'default';
carol = 'Carol Danvers';
@carol(function(){return this.carol})
test2() {
return `${this.name}!`;
}
}
const my = new MyClass();
const test2Val = my.test2();
console.log('Second', test2Val); // this prints Carol Danvers