我查看了 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)
时期望首先调用一个工厂,它将返回一个装饰器函数。
这是我编写的装饰器示例,它将状态属性添加到类中 由 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;
}
}
Do note, that the decorator in the example is a class decorator, which has a different signature
(target)
than the method decorator you are writing(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
实用函数中调用装饰器的逻辑,这使得他的代码更难理解。
希望这有帮助
关于javascript - 直接调用或作为工厂函数调用的 ES.next 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39863262/