0

I am trying to pass a method to a typescript decorator. I am able to do so when I do this as an inline arrow function. But I am not able to do this in the following way:

function preProcessor(preFn:any) {
    
    return function (
        target: any,
        propertyKey: string,
        descriptor: PropertyDescriptor
    ) {        
        descriptor.value = function (param:any) {
            return preFn(param);
        }
    };
}

class C {
    @preProcessor(this.capitalize)
    methodA(str: any) {
        console.log(str)    }

  capitalize = (x:any)=>{return x.toUpperCase()}

}

var c = new C()
console.log(c.methodA("samurai..."))

This works:

@preProcessor((x:any)=>{return x.toUpperCase()})
SamuraiJack
  • 4,160
  • 11
  • 60
  • 152
  • 1
    This is not possible. When the decorator runs, there is no `this` yet. Your best bet would be to pass the *name* of the method, i.e. `@preProcessor('capitalize')` – Bergi Sep 22 '20 at 22:17
  • How is sending name as a string going to work? @Bergi – SamuraiJack Sep 22 '20 at 22:23
  • Then you can call `this[methodName]()` inside the decorated method – Bergi Sep 22 '20 at 22:24
  • That seems to be working. One noob question though- I believe it's possible because `this` would refer to the context of the caller. Which is `class C` right? Therefore it will work because capitalize is inside class C. Is that correct? – SamuraiJack Sep 22 '20 at 22:28
  • 1
    No, [it refers to `c`](https://stackoverflow.com/q/3127429/1048572) or whatever you are calling `.methodA()` on. – Bergi Sep 22 '20 at 23:24
  • @Bergi isn't that same as what I said? O.o? I mean `this` will hold scope of class c instance on which method was called, right? – SamuraiJack Sep 22 '20 at 23:28
  • I was just taking you literally - the instance `c` is not the same as the class object `C`. And there is no "scope" for object properties. The object `c` inherits `methodA` from `C.prototype`, and has an own property `capitalize`. Notice you can also do `c.methodA.call({capitalize() { return x.toLowerCase(); }}, "Ooops")` where `this` does not refer to `c` and it will call a different capitalise function. – Bergi Sep 22 '20 at 23:32
  • @Bergi got it.. thanks – SamuraiJack Sep 22 '20 at 23:46

0 Answers0