【问题标题】:js apply decorator programmaticallyjs 以编程方式应用装饰器
【发布时间】:2018-05-24 06:45:54
【问题描述】:

我有一个类装饰器,想用它来为类中的所有方法应用另一个装饰器,但我不太确定如何在没有 @ 语法的情况下以编程方式应用装饰器:

@LogAllMethods
class User {
    greet() {
        console.log('Hello')
    }
}

function LogAllMethods(target) {
    for (const key in Object.keys(target.prototype)) {
        // apply LogMethod decorator
    }
}

function LogMethod(target, key, descriptor) {
    let method = descriptor.value
    decriptor.value = function(...args) {
        console.log(args)
        method.apply(this, ...args)
    }
}

【问题讨论】:

  • 你的目标是 ES5 还是 ES2015 ?
  • 您不使用@ 语法以编程方式执行此操作。您检查规范以了解 @ 语法的作用,然后从代码中执行。

标签: javascript typescript decorator


【解决方案1】:

你基本上只需要使用目标、键(方法名)和定义的描述符来调用装饰器函数:

function LogAllMethods<T>(target: new (...params: any[]) => T) {
    for (const key of Object.getOwnPropertyNames(target.prototype)) {
        let descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);
        descriptor = LogMethod(target.prototype, key, descriptor);
        if (descriptor) {
            Object.defineProperty(target.prototype, key, descriptor);
        }
    }
}

function LogMethod(target: any, key: symbol | string, descriptor: TypedPropertyDescriptor<any> = undefined) {

    if (descriptor) {
        let method = descriptor.value;
        if (method instanceof Function) {
            descriptor.value = function (...args: any[]) {
                console.log("Log", args)
                method.apply(this, ...args);
            }
        }
        return descriptor;
    } else {
        // descriptor is null for target es5 if the decorator is applied directly to the merhod
        let method = target[key];
        if (method instanceof Function) {
            target[key] = function (...args: any[]) {
                console.log("Log", args)
                method.apply(this, ...args);
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-26
    • 2016-03-08
    • 1970-01-01
    • 2011-04-13
    • 2011-10-05
    • 2023-03-03
    • 1970-01-01
    • 2015-02-01
    相关资源
    最近更新 更多