且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何避免硬编码?在装饰者

更新时间:2022-12-22 13:16:24

不要使用箭头功能。使用函数表达式:

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;
        }
    };
}

这样它会使用函数的这个调用日志时,code>上下文而不是的值。

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

顺便说一句,我建议编辑descriptor / value参数并返回,而不是通过返回一个新的描述符来覆盖它。这样你就可以保留当前属性中的属性,并且不会覆盖另一个装饰者可能对描述符做的事情:

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;
}

此答案中的更多详情 - 请参阅示例 - 没有参数>注释下的Bad vs Good示例

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