ES.下一个装饰器可以直接调用,也可以作为工厂函数调用
ES.next decorators that get called either directly or as a factory function
我看了一些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函数。
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
实用程序函数中调用装饰器,这使得他的代码更难遵循。
希望能有所帮助
相关文章:
- 函数未在Object.keys或Object.getOwnPropertyNames下列出,但可以调用
- 即使光标位于屏幕边缘,也可以跟踪鼠标速度
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 有什么方法可以调用外部URI方案吗
- 在下拉列表中的页面加载中已经选择了一个选项,该选项也可以更改
- javascript数组既可以是数字数组,也可以是关联数组
- 如何使用javascript函数创建可以调用javascript函数的聚合物元素
- 我需要一个注册按钮,它可以将数据发送到mySQL服务器,也可以在单击时重定向
- 在更改时,如果没有使用jquery更改,也可以删除对select元素的关注
- 即使使用jQuery DOM就绪事件,也无法调用null的方法addEventListener()
- 角度:创建可以调用作用域函数的自定义指令
- jQuery聚焦文本框并转到末尾,但也可以设置光标的位置,以便用户可以看到它
- 是否可以调用Google API获取地图图像并将图像保存在某个位置
- regex某个字符可以存在也可以不存在,但之后什么都没有
- 即使表单无效,也会调用HTML5表单提交处理程序
- 如何创建一个可以调用的函数,以使用JQplot显示多个条形图
- cordova应用程序是否可以调用android特定的操作
- 即使它在 Chrome 浏览器上不起作用,也可以单击
- 在设置 IIS Express 以识别 JSON 文件类型后 - VS 是否可以调用除纯文本之外的更好的编辑器
- ES.下一个装饰器可以直接调用,也可以作为工厂函数调用