How to avoid hard coded this? in Decorators

前端 未结 2 1577
深忆病人
深忆病人 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) {
        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"

提交回复
热议问题