类对象中的装饰器函数如何访问该对象内的属性。在下面的虚构示例中,this.name
未返回预期名称“JohnDoe”,它始终为空。
class First {
name:string
constructor(name:string) {
this.name = name
}
nameProperty(target: any, key: string) {
...
console.log(this.name); //<--- this is always empty. was expecting "JohnDoe"
...
}
}
let f = First("JohnDoe")
class Second {
@f.nameProperty
dummyName:string
}
答案 0 :(得分:1)
你正在失去this
。尝试用箭头函数捕获它:
class First {
name:string
constructor(name:string) {
this.name = name
}
nameProperty()
{
return (target: any, key: string) =>
{
console.log(this.name);
}
}
}
let f = new First("JohnDoe");
class Second {
@f.nameProperty()
dummyName:string
}