javascript 函数装饰器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31771856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Decorators on functions
提问by
I see that babel.js decorators (available in "stage 1") implement the spec at https://github.com/wycats/javascript-decorators. It appears that decorators are limited to (1) classes, (2) accessors, and (3) methods. In my case, I want to use decorators on plain old functions, as in
我看到 babel.js 装饰器(在“阶段 1”中可用)在https://github.com/wycats/javascript-decorators实现了规范。装饰器似乎仅限于 (1) 类、(2) 访问器和 (3) 方法。就我而言,我想在普通的旧函数上使用装饰器,如
@chainable
function foo() { }
where (just an example)
哪里(只是一个例子)
function chainable(fn) {
return function() {
fn.apply(this, arguments);
return this;
};
}
I don't see any logical reason why decorators should not be able to apply to functions. My question is, is there some way to accomplish this? Or is there some good reason why functions cannot be decorated?
我看不出装饰器不能应用于函数的任何合乎逻辑的原因。我的问题是,有没有办法做到这一点?或者有什么好的理由不能装饰函数?
It turns out there is an issue raised for this at https://github.com/wycats/javascript-decorators/issues/4.
事实证明,在https://github.com/wycats/javascript-decorators/issues/4上提出了一个问题。
回答by Axel Rauschmayer
To execute a decorator, you evaluate an expression and doing that prevents hoisting (even for a variable declaration, the right-hand side of an assignment stays put). Therefore, it is not compatible with function declarations being hoisted.
要执行装饰器,您需要评估一个表达式并防止提升(即使对于变量声明,赋值的右侧也保持不变)。因此,它与被提升的函数声明不兼容。
As a work-around, I suggested that function expressions, generator function expressions and arrow functions could be enabled to be decorated:
作为一种解决方法,我建议可以启用函数表达式、生成器函数表达式和箭头函数来装饰:
const func = @someDecorator('abc') (x, y) => { return x + y };
Alas, that wasn't met with much enthusiasm: Decorators for functions
唉,这并没有引起太多热情:函数装饰器
回答by Leonid Beschastny
You certainly have a point here.
你在这里肯定有道理。
But as neo_blackcappointed out, function decorator are not part of the ES7 decorators draft.
但正如neo_blackcap指出的那样,函数装饰器不是ES7 装饰器草案的一部分。
So, the best thing you can do is to start discussion on the corresponding trackerto attract community attention to your proposal.
所以,你能做的最好的事情就是开始讨论相应的跟踪器,以吸引社区对你的提议的关注。
ES7 decorators are on their first stage of developmentsecond stage of development, meaning that their API is still under development and could undergo any change.
回答by Neo Ko
I think the problem is function decorator has not been ES7 draft.
我认为问题是函数装饰器还没有 ES7 草案。
Of course, you still can implement your function decorator by yourself
当然,你仍然可以自己实现你的函数装饰器