How to avoid hard coded this? in Decorators

前端 未结 2 1557
深忆病人
深忆病人 2020-12-29 14:45

I have read \"How to implement a typescript decorator?\" and multiple sources but there is something that i have nor been able to do with decorators.

class F         


        
相关标签:
2条回答
  • 2020-12-29 15:10

    Don't use an arrow function. Use a function expression:

    function log(target: Object, key: string, value: any) {
        return {
            value: function(...args: any[]) {
                var a = args.map(a => JSON.stringify(a)).join();
                var result = value.value.apply(this, args);
                var r = JSON.stringify(result);
                console.log(`Call: ${key}(${a}) => ${r}`);
                return result;
            }
        };
    }
    

    That way it will use the function's this context instead of the value of this when log is called.


    By the way, I would recommend editing the descriptor/value parameter and return that instead of overwriting it by returning a new descriptor. That way you keep the properties currently in the descriptor and won't overwrite what another decorator might have done to the descriptor:

    function log(target: Object, key: string, descriptor: TypedPropertyDescriptor<any>) {
        var originalMethod = descriptor.value;
    
        descriptor.value = function(...args: any[]) {
            var a = args.map(a => JSON.stringify(a)).join();
            var result = originalMethod.apply(this, args);
            var r = JSON.stringify(result);
            console.log(`Call: ${key}(${a}) => ${r}`);
            return result;
        };
    
        return descriptor;
    }
    

    More details in this answer - See the "Bad vs Good" example under "Example - Without Arguments > Notes"

    0 讨论(0)
  • 2020-12-29 15:25

    I believe you can use

    var self = this;
    

    in order to preserve the 'this' at that specific point. Then, just use self at the later point where you would have wanted that particular this

    0 讨论(0)
提交回复
热议问题