【发布时间】:2019-10-04 23:14:33
【问题描述】:
请注意:这个问题是因为在运行我的修饰方法时使用了 GraphQL 解析器。这意味着this 的范围是undefined。但是,这个问题的基础知识对于遇到装饰器问题的任何人都很有用。
这是我想要使用的基本装饰器(我的有更多代码):
const someDecorator = (argPassed: any) => {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value;
// DO stuff here...
console.log(argPassed);
// Wrapping the original method
descriptor.value = (...args: any[]) => {
const result = originalMethod.apply(this, args);
return result;
};
};
};
我在装饰器中使用箭头函数,这是我可以让它返回某种范围的唯一方法,尽管与普通的 this 范围不同。
这是我正在使用的类和我正在装饰的方法:
class SomeClass {
constructor() {
}
@someDecorator('Passing this in...')
public doingSomething(argPassed: string) {
console.log(this); // Returns: { default: SomeClass { otherMethodInMyClass: [Function] } }
// Meaning i can't do this
// this.otherMethodInMyClass is not a function
this.otherMethodInMyClass(argPassed);
}
private otherMethodInMyClass = (argPassed: any) => {
// Let's go for it...
}
}
目前装饰器将doingSomething的作用域传回为:
{ default: SomeClass { otherMethodInMyClass: [Function] } }
当我不使用装饰器时:
SomeClass { doingSomething: [Function], otherMethodInMyClass: [Function] }
这是正常行为吗?如果没有,我做错了什么? 如果是这样,我如何允许我的方法在调用其他方法之后使用它自己的范围。
更新:
正如@jcalz 正确提到的,箭头函数没有自己的this 上下文。但是,当我在装饰器上使用非箭头函数时,this 返回为undefined。
提前致谢
【问题讨论】:
-
不要使用箭头函数作为方法,因为an arrow function does not get its own
thiscontext。请改用常规匿名函数。 -
感谢@jcalz,我尝试不使用箭头函数,但结果未定义。
-
另外@jcalz,如果您有一个工作示例,其中返回正确的上下文,请将其作为答案!
标签: typescript ts-node typescript-decorator