Rjk
Rjk

Reputation: 1474

Typescript: Access other functions/properties of a class inside a decorator declaration

How can a decorator function inside a class object access a property inside that object. In the below imaginary example this.name is not returning the expected name "JohnDoe", its always empty.

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

}

Upvotes: 0

Views: 652

Answers (1)

Amid
Amid

Reputation: 22332

You are loosing this. Try capture it with arrow function like 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

}

Upvotes: 1

Related Questions