ES.下一个装饰器可以直接调用,也可以作为工厂函数调用

ES.next decorators that get called either directly or as a factory function

本文关键字:也可以 调用 函数调用 工厂 下一个 ES      更新时间:2023-09-26

我看了一些ES的例子。下一个decorator,并注意到有可能使一个decorator作为一个接受参数的因子函数来应用,或者直接通过同时省略末尾的()来应用。

我设法让两种风格分别工作,作为工厂功能@decorate(withArgs),或直接@decorate,但不是两者!

下面是一个例子:https://github.com/jayphelps/core-decorators.js deprecate-alias-deprecated

class foo {
  @deprecate
  foo() {}
  @deprecate("with an optional string")
  bar() {}
}

我试着检查上面提到的源代码,但是以我有限的装饰器经验,我不知道如何设置这样的东西。


这是我如何设法让@decorate工作不使用任何参数

function decorate(target, key, descriptor) {
  // do some stuff and then return the new descriptor
}

,这里是我如何设法让@decorate(args)工作参数作为一个工厂函数:

function decorate(...args) {
  return function(target, key, descriptor) {
    // do some stuff using args and then return the new descriptor
  }
}

正如你所看到的,在这一点上,decorate foo()decorate(args) foo(),而不是两者。

在编写@decorator时,浏览器期望立即调用decorator函数,而在编写@decorator(args)时,浏览器期望首先调用一个工厂,它将返回一个decorator函数

下面是我写的一个装饰器的例子,它给一个类添加了一个state属性这是由redux 驱动的
export default function state (defaultState) {
    function reducer(state, action) {
        if (!state) {
            state = defaultState;
        }
        ...
    }
    function decorator (target) {...}
    // If 1st argument is a function, it means `@state` was written
    if (typeof defaultState === 'function') {
        let target = defaultState;
        defaultState = {};
        return decorator(target);
    } else {
        return decorator;
    }
}
请注意,示例中的装饰器是一个类装饰器有一个不同的签名(target)方法装饰器你是写(target, key, descriptor)

装饰器可以带或不带参数

import state from './decorators/redux-state'
@state({
    name: '',
})
class MyClass {
    ...
}
@state
class MyOtherClass {
    constructor(state= {name: ''}) {
        this.state = state;
    }
    ...
}

Jay Phelps正在抽象逻辑,以确定如何在decorate实用程序函数中调用装饰器,这使得他的代码更难遵循。

希望能有所帮助

相关文章: