Typescript:访问装饰器声明中类的其他函数/属性

时间:2016-08-26 04:56:55

标签: javascript typescript decorator

类对象中的装饰器函数如何访问该对象内的属性。在下面的虚构示例中,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

}

1 个答案:

答案 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

}