直接或作为工厂函数调用ES.next装饰器
问题描述:
我已经看过ES.next装饰器的一些例子,并注意到它可能使一个装饰器作为一个因子函数应用参数,或直接在最后同时省略()
。直接或作为工厂函数调用ES.next装饰器
我设法让两种款式分开使用,作为工厂功能@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(args)
当它预期工厂首次被调用,它会返回一个装饰功能。
下面是增加了一个状态属性由终极版
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;
}
...
}
周杰伦菲尔普斯被使用,则提取搞清楚装饰如何被调用的decorate
效用函数的逻辑,而的Makis他的代码难于跟随。
希望这会有所帮助
您是否编写了自己的@deprecate实现(如果是这样,发布它)?或者你难以让他们的例子工作? –
@RobM。我更新了这个问题以显示我的实现,我并不关心'deprecate'的实际实现。我试图让装饰者在最后使用或不使用'()'。 – Wazeem
嗨,如果我的答案解决了您的问题,您能否将其标记为已接受? – Dogoku