功能装饰器

时间:2018-12-28 15:33:42

标签: javascript function typescript decorator ecma

如我所见,装饰器通常可以与类和类内的方法一起使用。有没有办法使用带有常规功能的装饰器,如下面的代码所示:

@myDecorator()
function someFunction() {
  // do something
}

someFunction(); // running the function with the decorator.

2 个答案:

答案 0 :(得分:3)

不适用于the current proposal。装饰独立功能,对象初始化器及其内容或其他东西很可能是后续建议,但是当前建议仅允许装饰类及其内容。

答案 1 :(得分:2)

当前proposal的功能不支持装饰器

您可以通过简单的函数调用获得类似的结果:

function myDecorator<Args extends any[], R>(fn: (...a: Args)=> R): (...a:Args) =>R {
    return function (...a: Args) {
        console.log("Calling");
        return fn(...a);
    } 
}
const someFunction = myDecorator(function () {
    console.log("Call");
});

someFunction(); 
相关问题