7

I have this code

function changeFunc() {
    return function(target: any, title: string, descriptor: PropertyDescriptor) {

        descriptor.value = function () {
            console.log(this.name);
        };

        return descriptor;

    }
}


class Man {
    name: string = "asdsds";

    constructor(name: string) {
        this.name = name;
    }

    @changeFunc()
    getName() {
        console.log("Hello");
    }

}


var man = new Man('Manos Serifios');
man.getName();  

In other words i try (with the decorator) to change the method

getName() {  
    console.log("Hello");  
}  

with this

function () {
    console.log(this.name);
}

but this.name evaluated as undefined.

If i console log the "this" it seems that is the right(instance man).

2
  • maybe descriptor.value = function () { console.log(target.name); };. I am just guessing and have no experience with typescript decorators Commented Jan 12, 2018 at 0:30
  • @2pha no, i tried it Commented Jan 12, 2018 at 9:44

3 Answers 3

7

You don't have the context of a specific object instance inside the decorator method. The parameters are the following (from https://www.typescriptlang.org/docs/handbook/decorators.html):

Either the constructor function of the class for a static member, or the prototype of the class for an instance member.

The name of the member.

The Property Descriptor for the member.

Sign up to request clarification or add additional context in comments.

Comments

3

You can do a little Hack. Replace your code

descriptor.value = function () {
  console.log(this.name);
};

with this nice trick:

descriptor.value = function () {
  // Hack 
  const self = this as Man;
  console.log(self.name);
};

1 Comment

but if your decorator is used on hundreds of classes? and you would have to have your class defined in your decorator file and they are codependent.
0

@hackerman's answer worked for me, as it seems to just be a typing issue. An alternative solution would be to actively define the type of this for that function:

descriptor.value = function (this: Man) {
  console.log(this.name);
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.